home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_xemacs.idb / usr / freeware / lib / xemacs-20.4 / lisp / modes / reftex.el.z / reftex.el
Encoding:
Text File  |  1998-05-21  |  223.8 KB  |  5,976 lines

  1. ;; reftex.el --- Minor mode for doing \label, \ref and \cite in LaTeX
  2. ;; Copyright (c) 1997, 1998 Free Software Foundation, Inc.
  3.  
  4. ;; Version:    3.17 
  5. ;; Author:     Carsten Dominik <dominik@strw.LeidenUniv.nl>
  6. ;; Keywords:   tex
  7.  
  8. ;; This file is part of GNU Emacs.
  9.  
  10. ;; GNU Emacs is free software; you can redistribute it and/or modify
  11. ;; it under the terms of the GNU General Public License as published by
  12. ;; the Free Software Foundation; either version 2, or (at your option)
  13. ;; any later version.
  14.  
  15. ;; GNU Emacs is distributed in the hope that it will be useful,
  16. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  18. ;; GNU General Public License for more details.
  19.  
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs; see the file COPYING.  If not, write to the
  22. ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  23. ;; Boston, MA 02111-1307, USA.
  24.  
  25. ;;---------------------------------------------------------------------------
  26. ;;
  27. ;;; Commentary:
  28. ;;
  29. ;; RefTeX is a minor mode with distinct support for \ref, \label and
  30. ;; \cite commands in (multi-file) LaTeX documents.
  31. ;; Labels are created semi-automatically.  Definition context of labels is
  32. ;; provided when creating a reference.  Citations are simplified with
  33. ;; efficient database lookup.  A table of contents buffer provides easy
  34. ;; access to any part of a document.
  35. ;;
  36. ;;
  37. ;; To turn RefTeX Minor Mode on and off in a particular buffer, use
  38. ;; `M-x reftex-mode'.
  39. ;;
  40. ;; To turn on RefTeX Minor Mode for all LaTeX files, add one of the
  41. ;; following lines to your .emacs file:
  42. ;;
  43. ;;   (add-hook 'LaTeX-mode-hook 'turn-on-reftex)   ; with AUCTeX LaTeX mode
  44. ;;   (add-hook 'latex-mode-hook 'turn-on-reftex)   ; with Emacs latex mode
  45. ;;
  46. ;;
  47. ;; DOCUMENTATION
  48. ;; -------------
  49. ;;
  50. ;; There is an extensive texinfo document describing RefTeX in detail.
  51. ;; When you are getting reftex.el with the Emacs distribution, the
  52. ;; info files should already be installed.  To view this
  53. ;; documentation, use `M-x reftex-info RET'.
  54. ;;
  55. ;; The documentation is also available at
  56. ;;
  57. ;;     http://www.strw.leidenuniv.nl/~dominik/Tools/
  58. ;;
  59. ;;---------------------------------------------------------------------------
  60. ;; 
  61. ;; RefTeX in a Nutshell
  62. ;; ====================
  63. ;; 
  64. ;;   1. Labels and References
  65. ;;      RefTeX distinguishes labels for different environments.  It always
  66. ;;      knows if a certain label references a figure, table etc..  You can
  67. ;;      configure RefTeX to recognize any additional labeled environments
  68. ;;      you have defined yourself (variable REFTEX-LABEL-ALIST).
  69. ;;         - Creating Labels
  70. ;;           Type `C-c (' (`reftex-label') to insert a label at point.
  71. ;;           RefTeX will either
  72. ;;              - derive a label from context (default for section labels)
  73. ;; 
  74. ;;              - insert a simple label consisting of a prefix and a number
  75. ;;                (default for equations, enumerate items, and footnotes)
  76. ;;                or
  77. ;; 
  78. ;;              - prompt for a label string (figures and tables).
  79. ;; 
  80. ;;           Which labels are created how is configurable (variable
  81. ;;           REFTEX-INSERT-LABEL-FLAGS).
  82. ;; 
  83. ;;         - Referencing Labels
  84. ;;           Referencing labels is a snap and I promise you'll love it.
  85. ;;           In order to make a reference, type `C-c )'
  86. ;;           (`reftex-reference').  This shows an outline of the document
  87. ;;           with all labels of a certain type (figure, equation,...) and
  88. ;;           context of the label definition.  Selecting one of the labels
  89. ;;           inserts a `\ref' macro into the original buffer.  Online help
  90. ;;           during the selection is available with `?'.
  91. ;; 
  92. ;;   2. Citations
  93. ;;      After typing `C-c [' (`reftex-citation'), RefTeX will let you
  94. ;;      specify a regular expression to search in current BibTeX database
  95. ;;      files (as specified in the `\bibliography' command) and pull out a
  96. ;;      formatted list of matches for you to choose from.  The list is
  97. ;;      *formatted* and sorted, thus much easier to read than the raw
  98. ;;      database entries.  The text inserted into the buffer is by default
  99. ;;      just `\cite{KEY}', but can also contain author names and the year
  100. ;;      in a configurable way (variable REFTEX-CITE-FORMAT).
  101. ;; 
  102. ;;   3. Viewing Cross References
  103. ;;      With point on or anywhere before a `\ref' or `\cite' macro, press
  104. ;;      `C-c &' (`reftex-view-crossref').  This will display the
  105. ;;      corresponding label definition or BibTeX database entry in another
  106. ;;      window.
  107. ;; 
  108. ;;   4. Table of Contents
  109. ;;      Typing `C-c =' (`reftex-toc') will show a table of contents of the
  110. ;;      document.  From that buffer, you can jump quickly to every part of
  111. ;;      your document.
  112. ;; 
  113. ;;   5. Multifile Documents
  114. ;;      Multifile Domuments are fully supported. RefTeX will provide cross
  115. ;;      referencing information from all files which are part of the
  116. ;;      document. You may also use it to reference labels in external
  117. ;;      documents (in cooperation with the LaTeX package `xr').
  118. ;; 
  119. ;;   6. Document Parsing
  120. ;;      RefTeX needs to parse the document in order to find labels and
  121. ;;      other information.  It will do it automatically once, when you
  122. ;;      start working with a document.  Re-parsing should not be necessary
  123. ;;      too often since RefTeX updates its lists internally when you make
  124. ;;      a new label with `reftex-label'.  To enforce reparsing, call any
  125. ;;      of the commands described above with a raw `C-u' prefix, or press
  126. ;;      the `r' key in the label selection buffer or the table of contents
  127. ;;      buffer.
  128. ;;
  129. ;;---------------------------------------------------------------------------
  130. ;;
  131. ;; AUTHOR
  132. ;; ======
  133. ;;
  134. ;; Carsten Dominik <dominik@strw.LeidenUniv.nl>
  135. ;;
  136. ;;         with contributions from Stephen Eglen
  137. ;;
  138. ;; The newest version of RefTeX can be found at
  139. ;;
  140. ;;    http://www.strw.leidenuniv.nl/~dominik/Tools/
  141. ;;    ftp://strw.leidenuniv.nl/pub/dominik/
  142. ;;
  143. ;; The version at this site is compatible with Emacs 19 - the version
  144. ;; distributed with Emacs 20 is not.
  145. ;;
  146. ;; THANKS TO:
  147. ;; ---------
  148. ;; Thanks to the people on the Net who have used RefTeX and helped
  149. ;; developing it with their reports.  In particular thanks to
  150. ;;
  151. ;;    F. Burstall, Alastair Burt, Soren Dayton, Stephen Eglen,
  152. ;;    Karl Eichwalder, Peter Galbraith, Dieter Kraft, Adrian Lanz,
  153. ;;    Rory Molinari, Laurent Mugnier, Sudeep Kumar Palat, Daniel Polani,
  154. ;;    Robin Socha, Richard Stanton, Allan Strand, Jan Vroonhof,
  155. ;;    Christoph Wedler.
  156. ;;
  157. ;; The view crossref feature was inspired by the similar function in
  158. ;; Peter Galbraith's bib-cite.el.
  159. ;;
  160. ;; Finally thanks to Uwe Bolick who first got me (some years ago) into
  161. ;; supporting LaTeX labels and references with an Editor (which was
  162. ;; MicroEmacs at the time).
  163. ;;
  164. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  165. ;;
  166. ;; HISTORY
  167. ;; =======
  168. ;;
  169. ;; Here are the more important changes made to RefTeX since initial release.
  170. ;; Minor bug fixes are not mentioned.
  171. ;;
  172. ;; Version 1.00
  173. ;;    - released on 7 Jan 1997.
  174. ;; Version 1.04
  175. ;;    - Macros as wrappers, AMSTeX support, delayed context parsing for
  176. ;;      new labels.
  177. ;; Version 1.05
  178. ;;    - XEmacs port.
  179. ;; Version 1.07
  180. ;;    - RefTeX gets its own menu.
  181. ;; Version 1.09
  182. ;;    - Support for tex-main-file, an analogue for TeX-master.
  183. ;;    - MS-DOS support.
  184. ;; Version 2.00
  185. ;;    - Labels can be derived from context (default for sections).
  186. ;;    - Configuration of label insertion and label referencing revised.
  187. ;;    - Crossref fields in BibTeX database entries.
  188. ;;    - `reftex-toc' introduced (thanks to Stephen Eglen).
  189. ;; Version 2.03
  190. ;;    - Figure*, table*, Sidewaysfigure/table added to default environments.
  191. ;;    - `reftex-bibfile-ignore-list' introduced (thanks to Rory Molinari).
  192. ;;    - New functions `reftex-arg-label', `reftex-arg-ref', `reftex-arg-cite'.
  193. ;;    - Emacs/XEmacs compatibility reworked.  XEmacs 19.15 now is required.
  194. ;;    - `reftex-add-to-label-alist' (to be called from AUCTeX style files).
  195. ;;    - Finding context with a hook function.
  196. ;;    - Sorting BibTeX entries (new variable: `reftex-sort-bibtex-matches').
  197. ;; Version 2.05
  198. ;;    - Support for `custom.el'.
  199. ;;    - New function `reftex-grep-document' (thanks to Stephen Eglen).
  200. ;; Version 2.07
  201. ;;    - New functions `reftex-search-document', `reftex-query-replace-document'
  202. ;; Version 2.11
  203. ;;    - Submitted for inclusion to Emacs and XEmacs.
  204. ;; Version 2.14
  205. ;;    - THIS IS THE VERSION DISTRIBUTED WITH XEMACS 20.2.
  206. ;;    - Variable `reftex-plug-into-AUCTeX' simplifies cooperation with AUCTeX.
  207. ;; Version 2.17
  208. ;;    - THIS IS THE VERSION DISTRIBUTED WITH EMACS 20.1 and 20.2.
  209. ;;    - Label prefix expands % escapes with current file name and other stuff.
  210. ;;    - Citation format now with % escapes.  This is not backward compatible!
  211. ;;    - TEXINPUTS variable recognized when looking for input files.
  212. ;;    - Context can be the nth argument of a macro.
  213. ;;    - Searching in the select buffer is now possible (C-s and C-r).
  214. ;;    - Display and derive-label can use two different context methods.
  215. ;;    - AMSmath xalignat and xxalignat added.
  216. ;; Version 3.00
  217. ;;    - RefTeX should work better for very large projects:
  218. ;;       - The new parser works without creating a master buffer.
  219. ;;       - Rescanning can be limited to a part of a multifile document.
  220. ;;       - Information from the parser can be stored in a file.
  221. ;;    - RefTeX can deal with macros having a naked label as an argument.
  222. ;;    - Macros may have white space and newlines between arguments.
  223. ;;    - Multiple identical section headings no longer confuse `reftex-toc'.
  224. ;;    - RefTeX should work correctly in combination with buffer-altering
  225. ;;      packages like outline, folding, x-symbol, iso-cvt, isotex, etc.
  226. ;;    - All labeled environments discussed in `The LaTeX Companion' by
  227. ;;      Goossens, Mittelbach & Samarin, Addison-Wesley 1994) are part of
  228. ;;      RefTeX's defaults.
  229. ;; Version 3.03
  230. ;;    - Support for the LaTeX package `xr', for inter-document references.
  231. ;;    - A few (minor) Mule-related changes.
  232. ;;    - Fixed bug which could cause HUGE .rel files.
  233. ;;    - Search for input and .bib files with recursive path definitions.
  234. ;; Version 3.04
  235. ;;    - Fixed BUG in the `xr' support.
  236. ;; Version 3.05
  237. ;;    - Compatibility code now first checks for XEmacs feature.
  238. ;; Version 3.07
  239. ;;    - THIS IS THE VERSION DISTRIBUTED WITH XEMACS 20.3.
  240. ;;    - `Ref' menu improved.
  241. ;; Version 3.10
  242. ;;    - Fixed a bug which made reftex 3.07 fail on [X]Emacs version 19.
  243. ;;    - Removed unimportant code which caused OS/2 Emacs to crash.
  244. ;;    - All customization variables now accessible from menu.
  245. ;; Version 3.11
  246. ;;    - Fixed bug which led to naked label in (e.g.) footnotes.
  247. ;;    - Added scroll-other-window functions to RefTeX-Select.
  248. ;; Version 3.12
  249. ;;    - There are 3 new keymaps for customization: `reftex-toc-map',
  250. ;;      `reftex-select-label-map', `reftex-select-bib-map'.
  251. ;;    - Refontification uses more standard font-lock stuff.
  252. ;;    - When no BibTeX database files are specified, citations can also
  253. ;;      use \bibitem entries from a `thebibliography' environment.
  254. ;; Version 3.14
  255. ;;    - Selection buffers can be kept between selections: this is faster.
  256. ;;      See new variable `reftex-use-multiple-selection-buffers'.
  257. ;;    - Prefix interpretation of reftex-view-crossref changed.
  258. ;;    - Support for the `varioref' package (`v' key in selection buffer).
  259. ;; Version 3.16
  260. ;;    - New hooks `reftex-format-label-function', `reftex-format-ref-function',
  261. ;;      `reftex-format-cite-function'.
  262. ;;    - TeXInfo documentation completed.
  263. ;;    - Some restrictions in Label inserting and referencing removed.
  264. ;;    - New variable `reftex-default-bibliography'.
  265. ;; Version 3.17
  266. ;;    - THIS IS THE VERSION DISTRIBUTED WITH Emacs 20.3 and XEMACS 20.4.
  267. ;;    - Additional bindings in selection and *toc* buffers.  `g' redefined. 
  268. ;;    - New command `reftex-save-all-document-buffers'.
  269. ;;    - Magic word matching made more intelligent.
  270. ;;    - Selection process can switch to completion (with TAB).
  271. ;;    - \appendix is now recognized and influences section numbering.
  272. ;;    - File commentary shortened considerably (use Info documentation).
  273. ;;    - New option `reftex-no-include-regexps' to skip some include files.
  274. ;;    - New option `reftex-revisit-to-follow'.
  275. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  276. ;;
  277. ;;;;;;
  278.  
  279. ;;; Code:
  280.  
  281. (eval-when-compile (require 'cl))
  282.  
  283. ;; Stuff that needs to be there when we use defcustom
  284. ;; --------------------------------------------------
  285. (require 'custom)
  286.  
  287. (defvar reftex-tables-dirty t
  288.   "Flag showing if tables need to be re-computed.")
  289.  
  290. (eval-and-compile
  291.   (defun reftex-set-dirty (symbol value)
  292.     (setq reftex-tables-dirty t)
  293.     (set symbol value)))
  294.  
  295. (eval-and-compile
  296.   (defmacro reftex-fp (n)
  297.     (if (fboundp 'forward-point) 
  298.     (list 'forward-point n)
  299.       (list '+ '(point) n))))
  300.  
  301. ;;; Begin of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  302.  
  303. ;; Define the two constants which are needed during compilation
  304.  
  305. (eval-and-compile
  306. (defconst reftex-label-alist-builtin
  307.   '(
  308.     ;; Some aliases, mostly for backward compatibility
  309.     (Sideways    "Alias for -->rotating" (rotating))
  310.     (AMSTeX      "amsmath with eqref macro"
  311.                  ((nil ?e nil "~\\eqref{%s}")
  312.                   amsmath))
  313.  
  314.     ;; Individual package defaults
  315.     (amsmath "AMS-LaTeX math environments"
  316.      (("align"        ?e nil nil eqnarray-like)
  317.       ("gather"       ?e nil nil eqnarray-like)
  318.       ("multline"     ?e nil nil t)
  319.       ("flalign"      ?e nil nil eqnarray-like)
  320.       ("alignat"      ?e nil nil alignat-like)
  321.       ("xalignat"     ?e nil nil alignat-like)
  322.       ("xxalignat"    ?e nil nil alignat-like)
  323.       ("subequations" ?e nil nil t)))
  324.  
  325.     (endnotes "The \\endnote macro"
  326.      (("\\endnote[]{}" ?n nil nil 2 (regexp "Endnotes?"))))
  327.  
  328.     (fancybox "The Beqnarray environment"
  329.      (("Beqnarray" ?e nil nil eqnarray-like)))
  330.  
  331.     (floatfig "The floatingfigure environment"
  332.      (("floatingfigure" ?f nil nil caption)))
  333.  
  334.     (longtable   "The longtable environment"
  335.      (("longtable"  ?t nil nil caption)))
  336.  
  337.     (picinpar    "The figwindow and tabwindow environments"
  338.      (("figwindow" ?f nil nil 1)
  339.       ("tabwindow" ?f nil nil 1)))
  340.  
  341.     (rotating    "Sidewaysfigure and table"
  342.      (("sidewaysfigure" ?f nil nil caption)
  343.       ("sidewaystable"  ?t nil nil caption)))
  344.  
  345.     (subfigure   "Subfigure environments/macro"
  346.      (("subfigure"   ?f nil nil caption)
  347.       ("subfigure*"  ?f nil nil caption)
  348.       ("\\subfigure[]{}" ?f nil nil 1)))
  349.  
  350.     (supertab    "Supertabular environment"
  351.      (("supertabular" ?t nil nil "\\tablecaption{")))
  352.  
  353.     (wrapfig     "The wrapfigure environment"
  354.      (("wrapfigure" ?f nil nil caption)))
  355.  
  356.     ;; The LaTeX core stuff
  357.     (LaTeX       "LaTeX default environments"
  358.      (("section"   ?s "sec:" "~\\ref{%s}" (nil . t)
  359.        (regexp "Parts?" "Chapters?" "Chap\\." "Sections?" "Sect?\\."
  360.            "Paragraphs?" "Par\\."
  361.            "\\\\S" "\247" "Teile?" "Kapitel" "Kap\\." "Abschnitte?"
  362.            "Appendi\\(x\\|ces\\)" "App\\."  "Anh\"?ange?" "Anh\\."))
  363.  
  364.       ("enumerate" ?i "item:" "~\\ref{%s}" item
  365.        (regexp "Items?" "Punkte?"))
  366.       
  367.       ("equation"  ?e "eq:" "~(\\ref{%s})" t
  368.        (regexp "Equations?" "Eqs?\\." "Eqn\\." "Gleichung\\(en\\)?"  "Gl\\."))
  369.       ("eqnarray"  ?e "eq:" nil eqnarray-like)
  370.       
  371.       ("figure"    ?f "fig:" "~\\ref{%s}" caption
  372.        (regexp "Figure[sn]?" "Figs?\\." "Abbildung\\(en\\)?" "Abb\\."))
  373.       ("figure*"   ?f nil nil caption)
  374.       
  375.       ("table"     ?t "tab:" "~\\ref{%s}" caption
  376.        (regexp "Tables?" "Tab\\." "Tabellen?"))
  377.       ("table*"    ?t nil nil caption)
  378.       
  379.       ("\\footnote[]{}" ?n "note:" "~\\ref{%s}" 2
  380.        (regexp "Footnotes?" "Notes?"))
  381.       
  382.       ("any"       ?\  " "   "~\\ref{%s}" nil)))
  383.  
  384.     )
  385.   "The default label environment descriptions.
  386. Lower-case symbols correspond to a style file of the same name in the LaTeX
  387. distribution.  Mixed-case symbols are convenience aliases.")
  388.  
  389. (defconst reftex-cite-format-builtin
  390.   '(
  391.     (default "Default macro \\cite{%l}"
  392.       "\\cite{%l}")
  393.     (natbib "The Natbib package"
  394.      ((?\C-m . "\\cite{%l}")
  395.       (?t    . "\\citet{%l}")
  396.       (?T    . "\\citet*{%l}")
  397.       (?p    . "\\citep{%l}")
  398.       (?P    . "\\citep*{%l}")
  399.       (?e    . "\\citep[e.g.][]{%l}")
  400.       (?a    . "\\citeauthor{%l}")
  401.       (?y    . "\\citeyear{%l}")))
  402.     (harvard "The Harvard package"
  403.      ((?\C-m . "\\cite{%l}")
  404.       (?p    . "\\cite{%l}")
  405.       (?t    . "\\citeasnoun{%l}")
  406.       (?n    . "\\citeasnoun{%l}")
  407.       (?s    . "\\possessivecite{%l}")
  408.       (?e    . "\\citeaffixed{%l}{?}")
  409.       (?y    . "\\citeyear{%l}")
  410.       (?a    . "\\citename{%l}")))
  411.     (chicago "The Chicago package"
  412.      ((?\C-m . "\\cite{%l}")
  413.       (?t    . "\\citeN{%l}")
  414.       (?T    . "\\shortciteN{%l}")
  415.       (?p    . "\\cite{%l}")
  416.       (?P    . "\\shortcite{%l}")
  417.       (?a    . "\\citeA{%l}")
  418.       (?A    . "\\shortciteA{%l}")
  419.       (?y    . "\\citeyear{%l}")))
  420.     (astron "The Astron package"
  421.      ((?\C-m . "\\cite{%l}")
  422.       (?p    . "\\cite{%l}" )
  423.       (?t    . "%2a (\\cite{%l})")))
  424.     (author-year "Do-it-yourself Author-year"
  425.      ((?\C-m . "\\cite{%l}")
  426.       (?t    . "%2a (%y)\\nocite{%l}")
  427.       (?p    . "(%2a %y\\nocite{%l})")))
  428.     (locally     "Full info in parenthesis"
  429.      "(%2a %y, %j %v, %P, %e: %b, %u, %s %<)")
  430.     ;; undocumented feature: `%<' kills white space and punctuation locally.
  431.     )
  432.   "Builtin versions of for the citation format.
  433. The following conventions are valid for all alist entries:
  434. `?\C-m' should always point to a straight \\cite{%l} macro.
  435. `?t'    should point to a textual citation (citation as a noun).
  436. `?p'    should point to a parenthetical citation.")
  437. )
  438.  
  439. ;; Configuration Variables and User Options for RefTeX ------------------
  440.  
  441. (defgroup reftex nil
  442.   "LaTeX label and citation support."
  443.   :tag "RefTeX"
  444.   :link '(url-link :tag "Home Page" 
  445.            "http://strw.leidenuniv.nl/~dominik/Tools/")
  446.   :link '(emacs-commentary-link :tag "Commentary in reftex.el" "reftex.el")
  447.   :prefix "reftex-"
  448.   :group 'tex)
  449.  
  450. (defun reftex-customize ()
  451.   "Call the customize function with reftex as argument."
  452.   (interactive)
  453.   ;; Depending on the customize version we can call different functions.
  454.   (cond
  455.    ((fboundp 'customize-browse)
  456.     (customize-browse 'reftex))
  457.    ((fboundp 'customize-group)
  458.     (customize-group 'reftex))
  459.    ((fboundp 'customize)
  460.     (customize 'reftex))
  461.    (t (error "Custom.el not available"))))
  462.  
  463. (defun reftex-create-customize-menu ()
  464.   "Create a full customization menu for RefTeX."
  465.   (interactive)
  466.   (if (fboundp 'customize-menu-create)
  467.       (progn
  468.     (easy-menu-change 
  469.      '("Ref") "Customize"
  470.      `(["Browse RefTeX group" reftex-customize t]
  471.        "---"
  472.        ,(customize-menu-create 'reftex)
  473.        ["Set" Custom-set t]
  474.        ["Save" Custom-save t]
  475.        ["Reset to Current" Custom-reset-current t]
  476.        ["Reset to Saved" Custom-reset-saved t]
  477.        ["Reset to Standard Settings" Custom-reset-standard t]))
  478.     (message "\"Ref\"-menu now contains full customization menu"))
  479.     (error "Cannot expand menu (outdated version of cus-edit.el)")))
  480.  
  481. (defun reftex-show-commentary ()
  482.   "Use the finder to view the file documentation from `reftex.el'."
  483.   (interactive)
  484.   (require 'finder)
  485.   (finder-commentary "reftex.el"))
  486.  
  487. (defun reftex-info ()
  488.   "Read documentation for RefTeX in the info system."
  489.   (interactive)
  490.   (require 'info)
  491.   (Info-goto-node "(reftex)"))
  492.  
  493. ;; Support for \label and \ref --------------------------------------
  494.  
  495. (defgroup reftex-label-support nil
  496.   "Support for creation, insertion and referencing of labels in LaTeX."
  497.   :group 'reftex)
  498.  
  499. (defgroup reftex-defining-label-environments nil
  500.   "Definition of environments and macros to do with label."
  501.   :group 'reftex-label-support)
  502.  
  503. ;; Make a constant for the customization stuff
  504. (eval-and-compile
  505.   (defconst reftex-tmp
  506.     '((const  :tag "Default position" t)
  507.       (const  :tag "After label"      nil)
  508.       (number :tag "Macro arg nr" 1)
  509.       (regexp :tag "Regexp" "")
  510.       (const  :tag "Caption in float" caption)
  511.       (const  :tag "Item in list" item)
  512.       (const  :tag "Eqnarray-like" eqnarray-like)
  513.       (const  :tag "Alignat-like" alignat-like)
  514.       (symbol :tag "Function" my-func))))
  515.  
  516. (defcustom reftex-default-label-alist-entries
  517.   '(amsmath endnotes fancybox floatfig longtable picinpar
  518.         rotating subfigure supertab wrapfig LaTeX)
  519.   "Default label alist specifications.  LaTeX should be the last entry.
  520. This list describes the default label environments RefTeX should always use.
  521. It is probably a mistake to remove the LaTeX symbol from this list.
  522.  
  523. The options include:
  524. LaTeX      The standard LaTeX environments.
  525. Sideways   The sidewaysfigure and sidewaystable environments.
  526. AMSTeX     The math environments in the AMS-LaTeX amsmath package.
  527.  
  528. For the full list of options, try
  529.  
  530. M-x customize-variable RET reftex-default-label-alist-entries RET."
  531.   :group 'reftex-defining-label-environments
  532.   :set   'reftex-set-dirty
  533.   :type `(set
  534.       :indent 4
  535.           :inline t
  536.           :greedy t
  537.           ,@(mapcar
  538.              (function
  539.               (lambda (x)
  540.                 (list 'const ':tag (concat (symbol-name (nth 0 x))
  541.                                            ": " (nth 1 x))
  542.                       (nth 0 x))))
  543.              reftex-label-alist-builtin)))
  544.  
  545. (defcustom reftex-label-alist nil
  546.   "Alist with information on environments for \\label-\\ref use.
  547.  
  548. This docstring is easier to understand after reading the configuration
  549. examples in `reftex.el'.  Looking at the builtin defaults in the constant
  550. `reftex-label-alist-builtin' may also be instructive.
  551.  
  552. Set this variable to define additions and changes to the default.  The only
  553. things you MUST NOT change is that `?s' is the type indicator for section
  554. labels, and SPC for the `any' label type.  These are hard-coded at other
  555. places in the code.
  556.  
  557. Each list entry describes either an environment carrying a counter for use
  558. with \\label and \\ref, or a LaTeX macro defining a label as (or inside)
  559. one of its arguments.  The elements of each list entry are:
  560.  
  561. 0.  Name of the environment (like \"table\") or macro (like \"\\\\myfig\").
  562.     For macros, indicate the macro arguments for best results, as in
  563.     \"\\\\myfig[]{}{}{*}{}\".  Use square brackets for optional arguments,
  564.     a star to mark the label argument, if any.  The macro does not have to
  565.     have a label argument - you could also use \\label{..} inside one of
  566.     its arguments.
  567.     Special names: `section' for section labels, `any' to define a group
  568.     which contains all labels.
  569.     This may also be nil if the entry is only meant to change some settings
  570.     associated with the type indicator character (see below).
  571.  
  572. 1.  Type indicator character, like `?t', must be a printable ASCII character.
  573.     The type indicator is a single character which defines a label type.
  574.     Any label inside the environment or macro is assumed to belong to this
  575.     type.  The same character may occur several times in this list, to cover
  576.     cases in which different environments carry the same label type (like
  577.     `equation' and `eqnarray').
  578.  
  579. 2.  Label prefix string, like \"tab:\".
  580.     The prefix is a short string used as the start of a label.  It may be the
  581.     empty string.  The prefix may contain the following `%' escapes:
  582.        %f   Current file name with directory and extension stripped.
  583.        %F   Current file name relative to directory of master file.
  584.        %u   User login name, on systems which support this.
  585.  
  586.     Example: In a file `intro.tex', \"eq:%f:\" will become \"eq:intro:\").
  587.  
  588. 3.  Format string for reference insert in buffer.  `%s' will be replaced by
  589.     the label.
  590.     When the format starts with `~', the `~' will only be inserted if
  591.     there is not already a whitespace before point.
  592.  
  593. 4.  Indication on how to find the short context.
  594.     - If nil, use the text following the \\label{...} macro.
  595.     - If t, use
  596.        - the section heading for section labels.
  597.        - text following the \\begin{...} statement of environments.
  598.          (not a good choice for environments like eqnarray or enumerate,
  599.          where one has several labels in a single environment).
  600.        - text after the macro name (starting with the first arg) for macros.
  601.     - If an integer, use the nth argument of the macro.  As a special case,
  602.       1000 means to get text after the last macro argument.
  603.     - If a string, use as regexp to search *backward* from the label.  Context
  604.       is then the text following the end of the match.  E.g. putting this to
  605.       \"\\\\\\\\caption[[{]\" will use the caption in a figure or table
  606.       environment.
  607.       \"\\\\\\\\begin{eqnarray}\\\\|\\\\\\\\\\\\\\\\\" works for eqnarrays.
  608.     - If any of `caption', `item', `eqnarray-like', `alignat-like', this
  609.       symbol will internally be translated into an appropriate regexp
  610.       (see also the variable `reftex-default-context-regexps').
  611.     - If a function, call this function with the name of the environment/macro
  612.       as argument.  On call, point will be just after the \\label macro.  The
  613.       function is expected to return a suitable context string.  It should
  614.       throw an exception (error) when failing to find context.
  615.       As an example, here is a function returning the 10 chars following
  616.       the label macro as context:
  617.  
  618.         (defun my-context-function (env-or-mac)
  619.           (if (> (point-max) (+ 10 (point)))
  620.               (buffer-substring (point) (+ 10 (point)))
  621.             (error \"Buffer too small\")))
  622.  
  623.     Label context is used in two ways by RefTeX: For display in the label
  624.     menu, and to derive a label string.  If you want to use a different
  625.     method for each of these, specify them as a dotted pair.
  626.     E.g. `(nil . t)' uses the text after the label (nil) for display, and
  627.     text from the default position (t) to derive a label string.  This is
  628.     actually used for section labels.
  629.  
  630.     Setting the variable `reftex-use-text-after-label-as-context' to t
  631.     overrides the setting here.
  632.  
  633. 5.  List of magic words which identify a reference to be of this type.
  634.     If the word before point is equal to one of these words when calling
  635.     `reftex-reference', the label list offered will be automatically
  636.     restricted to labels of the correct type.
  637.     If the first element of this wordlist is the symbol `regexp', the
  638.     strings are interpreted as regular expressions.  RefTeX will add
  639.     a \"\\\\W\" to the beginning and other stuff to the end of the regexp.
  640.  
  641. If the type indicator characters of two or more entries are the same, RefTeX
  642. will use
  643.  - the first non-nil format and prefix
  644.  - the magic words of all involved entries.
  645.  
  646. Any list entry may also be a symbol.  If that has an association in
  647. `reftex-label-alist-builtin', the cddr of that association is spliced into the
  648. list.  However, builtin defaults should normally be set with the variable
  649. `reftex-default-label-alist-entries."
  650.   :group 'reftex-defining-label-environments
  651.   :set 'reftex-set-dirty
  652.   :type
  653.   `(repeat
  654.     (choice
  655.      :value ("" ?a nil nil nil nil)
  656.      (list :tag "Detailed label alist entry"
  657.            :value ("" ?a nil nil nil nil)
  658.            (choice    :tag "Environment or \\macro "
  659.                       (const  :tag "Ignore, just use typekey" nil)
  660.                       (string ""))
  661.            (character :tag "Typekey character     " ?a)
  662.            (choice    :tag "Label prefix string   "
  663.                       (const  :tag "Default" nil)
  664.                       (string :tag "String" "lab:"))
  665.            (choice    :tag "Label reference format"
  666.                       (const  :tag "Default" nil)
  667.                       (string :tag "String" "~\\ref{%s}"))
  668.            (choice :tag "Context"
  669.                    (choice
  670.                     :tag "1 method"
  671.                     ,@reftex-tmp)
  672.                    (cons :tag "Split methods"
  673.                          (choice
  674.                           :tag "  Display context     "
  675.                           ,@reftex-tmp)
  676.                          (choice
  677.                           :tag "  Derive label context"
  678.                           ,@reftex-tmp)))
  679.        (repeat :tag "List of Magic Words" (string)))
  680.      (choice
  681.       :tag "Package"
  682.       :value AMSTeX
  683.       ,@(mapcar
  684.          (function
  685.           (lambda (x)
  686.             (list 'const ':tag (concat (symbol-name (nth 0 x)))
  687.                   (nth 0 x))))
  688.          reftex-label-alist-builtin)))))
  689.  
  690. ;; LaTeX section commands and level numbers
  691. (defcustom reftex-section-levels
  692.   '(
  693.     ("part"            . 0)
  694.     ("chapter"         . 1)
  695.     ("section"         . 2)
  696.     ("subsection"      . 3)
  697.     ("subsubsection"   . 4)
  698.     ("paragraph"       . 5)
  699.     ("subparagraph"    . 6)
  700.     ("subsubparagraph" . 7)
  701.     )
  702.   "Commands and levels used for defining sections in the document.
  703. The car of each cons cell is the name of the section macro.  The cdr is a
  704. number indicating its level."
  705.   :group 'reftex-defining-label-environments
  706.   :set 'reftex-set-dirty
  707.   :type '(repeat
  708.           (cons (string :tag "sectioning macro" "")
  709.                 (number :tag "level           " 0))))
  710.  
  711. (defcustom reftex-default-context-regexps
  712.   '((caption       . "\\\\\\(rot\\)?caption\\*?[[{]")
  713.     (item          . "\\\\item\\(\\[[^]]*\\]\\)?")
  714.     (eqnarray-like . "\\\\begin{%s}\\|\\\\\\\\")
  715.     (alignat-like  . "\\\\begin{%s}{[0-9]*}\\|\\\\\\\\"))
  716. "Alist with default regular expressions for finding context.
  717. The form (format regexp (regexp-quote environment)) is used to calculate
  718. the final regular expression - so %s will be replaced with the environment
  719. or macro."
  720.   :group 'reftex-defining-label-environments
  721.   :type '(repeat (cons (symbol) (regexp))))
  722.   
  723. (defcustom reftex-use-text-after-label-as-context nil
  724.   "*t means, grab context from directly after the \\label{..} macro.
  725. This is the fastest method for obtaining context of the label definition, but
  726. requires discipline when placing labels.  Setting this variable to t takes
  727. precedence over the individual settings in `reftex-label-alist'.
  728. This variable may be set to t, nil, or a string of label type letters
  729. indicating the label types for which it should be true."
  730.   :group 'reftex-defining-label-environments
  731.   :set 'reftex-set-dirty
  732.   :type '(choice
  733.           (const :tag "on" t) (const :tag "off" nil)
  734.           (string :tag "Selected label types")))
  735.  
  736. ;; Label insertion
  737.  
  738. (defgroup reftex-making-and-inserting-labels nil
  739.   "Options on how to create new labels."
  740.   :group 'reftex-label-support)
  741.  
  742. (defcustom reftex-insert-label-flags '("s" "sft")
  743.   "Flags governing label insertion.  First flag DERIVE, second flag PROMPT.
  744.  
  745. If DERIVE is t, RefTeX will try to derive a sensible label from context.
  746. A section label for example will be derived from the section heading.
  747. The conversion of the context to a legal label is governed by the
  748. specifications given in `reftex-derive-label-parameters'.
  749. If RefTeX fails to derive a label, it will prompt the user.
  750. If DERIVE is nil, the label generated will consist of the prefix and a
  751. unique number, like `eq:23'.
  752.  
  753. If PROMPT is t, the user will be prompted for a label string.  The prompt will
  754. already contain the prefix, and (if DERIVE is t) a default label derived from
  755. context.  When PROMPT is nil, the default label will be inserted without
  756. query.
  757.  
  758. So the combination of DERIVE and PROMPT controls label insertion.  Here is a
  759. table describing all four possibilities:
  760.  
  761. DERIVE   PROMPT      ACTION
  762. -------------------------------------------------------------------------
  763.  nil     nil     Insert simple label, like eq:22 or sec:13.  No query.
  764.  nil     t       Prompt for label.
  765.  t       nil     Derive a label from context and insert without query.
  766.  t       t       Derive a label from context and prompt for confirmation.
  767.  
  768. Each flag may be set to t, nil, or a string of label type letters
  769. indicating the label types for which it should be true.  The strings work
  770. like character classes.
  771. Thus, the combination may be set differently for each label type.  The
  772. default settings \"s\" and \"sft\" mean: Derive section labels from headings
  773. (with confirmation).  Prompt for figure and table labels.  Use simple labels
  774. without confirmation for everything else.
  775. The available label types are: s (section), f (figure), t (table), i (item),
  776. e (equation), n (footnote), plus any definitions in `reftex-label-alist'."
  777.   :group 'reftex-making-and-inserting-labels
  778.   :type  '(list (choice :tag "Derive label from context"
  779.                          (const  :tag "always" t)
  780.                          (const  :tag "never" nil)
  781.                          (string :tag "selected label types" ""))
  782.                 (choice :tag "Prompt for label string  "
  783.                         :entry-format "  %b %v"
  784.                         (const  :tag "always" t)
  785.                         (const  :tag "never" nil)
  786.                         (string :tag "selected label types" ""))))
  787.  
  788. (defcustom reftex-derive-label-parameters '(3 20 t 1 "-"
  789.          ("the" "on" "in" "off" "a" "for" "by" "of" "and" "is"))
  790.   "Parameters for converting a string into a label.
  791. NWORDS      Number of words to use.
  792. MAXCHAR     Maximum number of characters in a label string.
  793. ILLEGAL     nil: Throw away any words containing characters illegal in labels.
  794.             t:   Throw away only the illegal characters, not the whole word.
  795. ABBREV      nil: Never abbreviate words.
  796.             t:   Always abbreviate words (see `reftex-abbrev-parameters').
  797.             not t and not nil: Abbreviate words if necessary to shorten
  798.                                label string below MAXCHAR.
  799. SEPARATOR   String separating different words in the label.
  800. IGNOREWORDS List of words which should not be part of labels."
  801.   :group 'reftex-making-and-inserting-labels
  802.   :type  '(list (integer :tag "Number of words            "  3)
  803.                 (integer :tag "Maximum label length       " 20)
  804.                 (choice  :tag "Illegal characters in words"
  805.                          (const :tag "throw away entire word" nil)
  806.                          (const :tag "throw away single chars" t))
  807.                 (choice  :tag "Abbreviate words           "
  808.                          (const :tag "never" nil)
  809.                          (const :tag "always" t)
  810.                          (const :tag "when label is too long" 1))
  811.                 (string  :tag "Separator between words    " "-")
  812.                 (repeat  :tag "Ignore words"
  813.                          :entry-format "           %i %d %v"
  814.                          (string :tag ""))))
  815.  
  816. (defcustom reftex-label-illegal-re "[\000-\040\177-\377\\\\#$%&~^_{}]"
  817.   "Regexp matching characters not legal in labels.
  818. For historic reasons, this character class comes *with* the [] brackets."
  819.   :group 'reftex-making-and-inserting-labels
  820.   :type '(regexp :tag "Character class"))
  821.  
  822. (defcustom reftex-abbrev-parameters '(4 2 "^saeiou" "aeiou")
  823.   "Parameters for abbreviation of words.
  824. MIN-CHARS    Minimum number of characters remaining after abbreviation.
  825. MIN-KILL     Minimum number of characters to remove when abbreviating words.
  826. BEFORE       Character class before abbrev point in word.
  827. AFTER        Character class after  abbrev point in word."
  828.   :group 'reftex-making-and-inserting-labels
  829.   :type '(list
  830.           (integer :tag "Minimum chars per word" 4)
  831.           (integer :tag "Shorten by at least   " 2)
  832.           (string  :tag "cut before char class " "^saeiou")
  833.           (string  :tag "cut after  char class " "aeiou")))
  834.  
  835. (defcustom reftex-format-label-function nil
  836.   "Function which produces the string to insert as a label definition.
  837. Normally should be nil, unless you want to do something fancy.
  838. The function will be called with two arguments, the LABEL and the DEFAULT
  839. FORMAT, which usually is `\label{%s}'.  The function should return the
  840. string to insert into the buffer."
  841.   :group 'reftex-making-and-inserting-labels
  842.   :type 'function)
  843.  
  844. ;; Label referencing
  845.  
  846. (defgroup reftex-referencing-labels nil
  847.   "Options on how to reference labels."
  848.   :group 'reftex-label-support)
  849.  
  850. (eval-and-compile
  851.   (defconst reftex-tmp
  852.     '((const :tag "on" t)
  853.       (const :tag "off" nil)
  854.       (string :tag "Selected label types"))))
  855.  
  856. (defcustom reftex-label-menu-flags '(t t nil nil nil nil t nil)
  857.   "List of flags governing the label menu makeup.
  858. The flags are:
  859.  
  860. TABLE-OF-CONTENTS  Show the labels embedded in a table of context.
  861. SECTION-NUMBERS    Include section numbers (like 4.1.3) in table of contents.
  862. COUNTERS           Show counters.  This just numbers the labels in the menu.
  863. NO-CONTEXT         Non-nil means do NOT show the short context.
  864. FOLLOW             Follow full context in other window.
  865. SHOW-COMMENTED     Show labels from regions which are commented out.
  866. MATCH-IN-TOC       Searches in label menu will also match in toc lines.
  867. SHOW FILES         Show Begin and end of included files.
  868.  
  869. Each of these flags can be set to t or nil, or to a string of type letters
  870. indicating the label types for which it should be true.  These strings work
  871. like character classes in regular expressions.  Thus, setting one of the
  872. flags to \"sf\" makes the flag true for section and figure labels, nil
  873. for everything else.  Setting it to \"^ft\" makes it the other way round.
  874. The available label types are: s (section), f (figure), t (table), i (item),
  875. e (equation), n (footnote), plus any definitions in `reftex-label-alist'.
  876.  
  877. Most options can also be switched from the label menu itself - so if you
  878. decide here to not have a table of contents in the label menu, you can still
  879. get one interactively during selection from the label menu."
  880.   :group 'reftex-referencing-labels
  881.   :type
  882.   `(list
  883.     (choice :tag "Embed in table of contents      " ,@reftex-tmp)
  884.     (choice :tag "Show section numbers            " ,@reftex-tmp)
  885.     (choice :tag "Show individual counters        " ,@reftex-tmp)
  886.     (choice :tag "Hide short context              " ,@reftex-tmp)
  887.     (choice :tag "Follow context in other window  " ,@reftex-tmp)
  888.     (choice :tag "Show commented labels           " ,@reftex-tmp)
  889.     (choice :tag "Searches match in toc lines     " ,@reftex-tmp)
  890.     (choice :tag "Show begin/end of included files" ,@reftex-tmp)))
  891.  
  892. (defcustom reftex-vref-is-default nil
  893.   "*Non-nil means, the varioref macro \\vref is used as default.
  894. In the selection buffer, the `v' key toggles the reference macro between 
  895. `\\ref' and `\\vref'.  The value of this variable determines the default
  896. which is active when entering the selection process.
  897. Instead of nil or t, this may also be a string of type letters indicating
  898. the label types for which it should be true."
  899.   :group  'reftex-referencing-labels
  900.   :type `(choice :tag "\\vref is default macro" ,@reftex-tmp))
  901.  
  902. (defcustom reftex-level-indent 2
  903.   "*Number of spaces to be used for indentation per section level."
  904.   :group 'reftex-referencing-labels
  905.   :type '(integer))
  906.  
  907. (defcustom reftex-refontify-context 1
  908.   "*Non-nil means, re-fontify the context in the label menu with font-lock.
  909. This slightly slows down the creation of the label menu.  It is only necessary
  910. when you definitely want the context fontified.
  911.  
  912. This option may have 3 different values:
  913. nil  Never refontify.
  914. t    Always refontify.
  915. 1    Refontify when absolutely necessary, e.g. when with the x-symbol package.
  916. The option is ignored when `reftex-use-fonts' is nil."
  917.   :group 'reftex-referencing-labels
  918.   :type '(choice
  919.           (const :tag "Never" nil)
  920.           (const :tag "Always" t)
  921.           (const :tag "When necessary" 1)))
  922.  
  923. (defcustom reftex-guess-label-type t
  924.   "*Non-nil means, `reftex-reference' will try to guess the label type.
  925. To do that, RefTeX will look at the word before the cursor and compare it with
  926. the words given in `reftex-label-alist'.  When it finds a match, RefTeX will
  927. immediately offer the correct label menu - otherwise it will prompt you for
  928. a label type.  If you set this variable to nil, RefTeX will always prompt."
  929.   :group 'reftex-referencing-labels
  930.   :type '(boolean))
  931.  
  932. (defcustom reftex-format-ref-function nil
  933.   "Function which produces the string to insert as a reference.
  934. Normally should be nil, because the format to insert a reference can 
  935. already be specified in `reftex-label-alist'.
  936. The function will be called with two arguments, the LABEL and the DEFAULT
  937. FORMAT, which normally is `~\ref{%s}'.  The function should return the
  938. string to insert into the buffer."
  939.   :group 'reftex-referencing-labels
  940.   :type 'function)
  941.  
  942. ;; BibteX citation configuration ----------------------------------------
  943.  
  944. (defgroup reftex-citation-support nil
  945.   "Support for referencing bibliographic data with BibTeX."
  946.   :group 'reftex)
  947.  
  948. (defcustom reftex-bibpath-environment-variables '("BIBINPUTS" "TEXBIB")
  949.   "*List of env vars which might contain the path to BibTeX database files."
  950.   :group 'reftex-citation-support
  951.   :set 'reftex-set-dirty
  952.   :type '(repeat (string :tag "Environment variable")))
  953.  
  954. (defcustom reftex-bibfile-ignore-list nil
  955.   "*List of files in \\bibliography{..} RefTeX should *not* parse.
  956. The file names have to be in the exact same form as in the bibliography
  957. macro - i.e. without the `.bib' extension.
  958. Intended for files which contain only `@string' macro definitions and the
  959. like, which are ignored by RefTeX anyway."
  960.   :group 'reftex-citation-support
  961.   :set 'reftex-set-dirty
  962.   :type '(repeat (string :tag "File name")))
  963.  
  964. (defcustom reftex-default-bibliography nil
  965.   "*List of BibTeX database file which should be used if none are specified.
  966. When `reftex-citation' is called from a document which has neither a
  967. `\bibliography{..}' statement nor a `thebibliography' environment,
  968. RefTeX will scan these files instead.  Intended for using
  969. `reftex-citation' in non-LaTeX files."
  970.   :group 'reftex-citation-support
  971.   :type '(repeat (file)))
  972.  
  973. (defcustom reftex-sort-bibtex-matches 'reverse-year
  974.   "*Sorting of the entries found in BibTeX databases by reftex-citation.
  975. Possible values:
  976. nil            Do not sort entries.
  977. 'author        Sort entries by author name.
  978. 'year          Sort entries by increasing year.
  979. 'reverse-year  Sort entries by decreasing year."
  980.   :group 'reftex-citation-support
  981.   :type '(choice (const :tag "not" nil)
  982.                  (const :tag "by author" author)
  983.                  (const :tag "by year"   year)
  984.                  (const :tag "by year, reversed" reverse-year)))
  985.  
  986. (defcustom reftex-cite-format 'default
  987.   "*The format of citations to be inserted into the buffer.
  988. It can be a string or an alist.  In the simplest case this is just
  989. the string \"\\cite{%l}\", which is also the default.  See the
  990. definition of `reftex-cite-format-builtin' for more complex examples.
  991.  
  992. If `reftex-cite-format' is a string, it will be used as the format.
  993. In the format, the following percent escapes will be expanded.
  994.  
  995. %l   The BibTeX label of the citation.
  996. %a   List of author names, see also `reftex-cite-punctuation.
  997. %2a  Like %a, but abbreviate more than 2 authors like Jones et al.
  998. %A   First author name only.
  999. %e   Works like %a, but on list of editor names. (%2e and %E work a well)
  1000.  
  1001. It is also possible to access all other BibTeX database fields:
  1002. %b booktitle     %c chapter        %d edition    %h howpublished
  1003. %i institution   %j journal        %k key        %m month
  1004. %n number        %o organization   %p pages      %P first page
  1005. %r address       %s school         %u publisher  %t title
  1006. %v volume        %y year
  1007.  
  1008. Usually, only %l is needed.  Try, however, (setq reftex-comment-citations t).
  1009.  
  1010. Beware that all this only works when using BibTeX database files.  When
  1011. citations are made from the \\bibitems in an explicit thebibliography
  1012. environment, only %l is available.
  1013.  
  1014. If `reftex-cite-format' is an alist of characters and strings, the user
  1015. will be prompted for a character to select one of the possible format
  1016. strings.
  1017.   In order to configure this variable, you can either set
  1018. `reftex-cite-format' directly yourself or set it to the SYMBOL of one of
  1019. the predefined styles (see `reftex-cite-format-builtin').  E.g.:
  1020. (setq reftex-cite-format 'harvard)"
  1021.   :group 'reftex-citation-support
  1022.   :type
  1023.   `(choice
  1024.     :format "%{%t%}: \n%[Value Menu%] %v"
  1025.     (radio :tag "Symbolic Builtins"
  1026.            :indent 4
  1027.            :value default
  1028.            ,@(mapcar
  1029.               (function
  1030.                (lambda (x)
  1031.                  (list 'const ':tag (concat (symbol-name (nth 0 x))
  1032.                                             ": " (nth 1 x))
  1033.                        (nth 0 x))))
  1034.               reftex-cite-format-builtin))
  1035.     (string :tag "format string" "\\cite{%l}")
  1036.     (repeat :tag "key-ed format strings"
  1037.             :value ((?\r . "\\cite{%l}")
  1038.                     (?t  . "\\cite{%l}") (?p . "\\cite{%l}"))
  1039.             (cons (character :tag "Key character" ?\r)
  1040.                   (string    :tag "Format string" "")))))
  1041.  
  1042. (defcustom reftex-comment-citations nil
  1043.   "*Non-nil means add a comment for each citation describing the full entry.
  1044. The comment is formatted according to `reftex-cite-comment-format'."
  1045.   :group 'reftex-citation-support
  1046.   :type '(boolean))
  1047.  
  1048. (defcustom reftex-cite-comment-format
  1049.   "%% %2a %y, %j %v, %P, %e: %b, %u, %s %<\n"
  1050.   "Citation format used for commented citations.  Must NOT contain %l."
  1051.   :group 'reftex-citation-support
  1052.   :type '(string))
  1053.  
  1054. (defcustom reftex-cite-punctuation '(", " " \\& " " {\\it et al.}")
  1055.   "Punctuation for formatting of name lists in citations.
  1056. This is a list of 3 strings.
  1057. 1. normal names separator, like \", \"     in Jones, Brown and Miller
  1058. 2. final names separator,  like \" and \"  in Jones, Brown and Miller
  1059. 3. The \"et al\" string,   like \" {\\it et al.}\" in Jones {\\it et al.}"
  1060.   :group 'reftex-citation-support
  1061.   :type '(list
  1062.           (string :tag "Separator for names            ")
  1063.           (string :tag "Separator for last name in list")
  1064.           (string :tag "string used as et al.          ")))
  1065.  
  1066. (defcustom reftex-format-cite-function nil
  1067.   "Function which produces the string to insert as a citation.
  1068. Normally should be nil, because the format to insert a reference can 
  1069. already be specified in `reftex-cite-format'.
  1070. The function will be called with two arguments, the CITATION KEY and the
  1071. DEFAULT FORMAT, which is taken from `reftex-cite-format'.  The function
  1072. should return the string to insert into the buffer."
  1073.   :group 'reftex-citation-support
  1074.   :type 'function)
  1075. ;; Table of contents configuration --------------------------------------
  1076.  
  1077. (defgroup reftex-table-of-contents-browser nil
  1078.   "A multifile table of contents browser."
  1079.   :group 'reftex)
  1080.  
  1081. (defcustom reftex-toc-follow-mode nil
  1082.   "*Non-nil means, point in *toc* buffer will cause other window to follow.
  1083. The other window will show the corresponding part of the document.
  1084. This flag can be toggled from within the *toc* buffer with the `f' key."
  1085.   :group 'reftex-table-of-contents-browser
  1086.   :type '(boolean))
  1087.  
  1088. ;; Tuning the parser ----------------------------------------------------
  1089.  
  1090. (defgroup reftex-optimizations-for-large-documents nil
  1091.   "Configuration of parser speed and memory usage."
  1092.   :group 'reftex)
  1093.  
  1094. (defcustom reftex-keep-temporary-buffers 1
  1095.   "*Non-nil means, keep buffers created for parsing and lookup.
  1096. RefTeX sometimes needs to visit files related to the current document.
  1097. We distinguish files visited for
  1098. PARSING: Parts of a multifile document loaded when (re)-parsing the document.
  1099. LOOKUP:  BibTeX database files and TeX files loaded to find a reference,
  1100.          to display label context, etc.
  1101. The created buffers can be kept for later use, or be thrown away immediately
  1102. after use, depending on the value of this variable:
  1103.  
  1104. nil  Throw away as much as possible.
  1105. t    Keep everything.
  1106. 1    Throw away buffers created for parsing, but keep the ones created
  1107.      for lookup.
  1108.  
  1109. If a buffer is to be kept, the file is visited normally (which is potentially
  1110. slow but will happen only once).
  1111. If a buffer is to be thrown away, the initialization of the buffer depends
  1112. upon the variable `reftex-initialize-temporary-buffers'."
  1113.   :group 'reftex-miscellaneous-configurations
  1114.   :type '(choice
  1115.           (const :tag "Throw away everything" nil)
  1116.           (const :tag "Keep everything" t)
  1117.           (const :tag "Keep lookup buffers only" 1)))
  1118.  
  1119. (defcustom reftex-initialize-temporary-buffers nil
  1120.   "*Non-nil means do initializations even when visiting file temporarily.
  1121. When nil, RefTeX may turn off find-file hooks and other stuff to briefly
  1122. visit a file.
  1123. When t, the full default initializations are done (find-file-hook etc.).
  1124. Instead of t or nil, this variable may also be a list of hook functions to
  1125. do a minimal initialization."
  1126.   :group 'reftex-miscellaneous-configurations
  1127.   :type '(choice
  1128.           (const :tag "Read files literally" nil)
  1129.           (const :tag "Fully initialize buffers" t)
  1130.           (repeat :tag "Hook functions" :value (nil)
  1131.            (function-item))))
  1132.  
  1133. (defcustom reftex-no-include-regexps '("\\.pstex_t\\'") ; default for x-symbol
  1134.   "*List of regular expressions to exclude certain input files from parsing.
  1135. If the name of a file included via \\include or \\input is matched by any
  1136. of the regular expressions in this list, that file is not parsed by RefTeX."
  1137.   :group 'reftex-optimizations-for-large-documents
  1138.   :type '(repeat (regexp)))
  1139.  
  1140. (defcustom reftex-enable-partial-scans nil
  1141.   "*Non-nil means, re-parse only 1 file when asked to re-parse.
  1142. Re-parsing is normally requested with a `C-u' prefix to many RefTeX commands,
  1143. or with the `r' key in menus.  When this option is t in a multifile document,
  1144. we will only parse the current buffer, or the file associated with the label
  1145. or section heading near point in a menu.  Requesting re-parsing of an entire
  1146. multifile document then requires a `C-u C-u' prefix or the capital `R' key
  1147. in menus."
  1148.   :group 'reftex-optimizations-for-large-documents
  1149.   :type 'boolean)
  1150.  
  1151. (defcustom reftex-allow-automatic-rescan t
  1152.   "*Non-nil means, RefTeX may rescan the document when this seems necessary.
  1153. Currently this applies only to rescanning after label insertion, when
  1154. the new label cannot be inserted correctly into the internal label
  1155. list."
  1156.   :group 'reftex-optimizations-for-large-documents
  1157.   :type 'boolean)
  1158.  
  1159. (defcustom reftex-save-parse-info nil
  1160.   "*Non-nil means, save information gathered with parsing in a file.
  1161. The file MASTER.rel in the same directory as MASTER.tex is used to save the
  1162. information.  When this variable is t, 
  1163. - accessing the parsing information for the first time in an editing session
  1164.   will read that file (if available) instead of parsing the document.
  1165. - each time (part of) the document is rescanned, a new version of the file
  1166.   is written."
  1167.   :group 'reftex-optimizations-for-large-documents
  1168.   :type 'boolean)
  1169.  
  1170. (defcustom reftex-use-multiple-selection-buffers nil
  1171.   "*Non-nil means use a separate selection buffer for each label type.
  1172. These buffers are kept from one selection to the next and need not to be
  1173. created for each use - so the menu generally comes up faster.  The
  1174. selection buffers will be erased (and therefore updated) automatically
  1175. when new labels in its category are added.  See the variable
  1176. `reftex-auto-update-selection-buffers'."
  1177.   :group 'reftex-optimizations-for-large-documents
  1178.   :type 'boolean)
  1179.  
  1180. (defcustom reftex-auto-update-selection-buffers t
  1181.   "*Non-nil means, selection buffers will be updated automatically.
  1182. When a new label is defined with `reftex-label', all selection buffers
  1183. associated with that label category are emptied, in order to force an
  1184. update upon next use.  When nil, the buffers are left alone and have to be
  1185. updated by hand, with the `g' key from the label selection process.
  1186. The value of this variable will only have any effect when
  1187. `reftex-use-multiple-selection-buffers' is non-nil."
  1188.   :group 'reftex-optimizations-for-large-documents
  1189.   :type 'boolean)
  1190.  
  1191. ;; Miscellaneous configurations -----------------------------------------
  1192.  
  1193. (defgroup reftex-miscellaneous-configurations nil
  1194.   "Collection of further configurations."
  1195.   :group 'reftex)
  1196.  
  1197. (defcustom reftex-extra-bindings nil
  1198.   "Non-nil means, make additional key bindings on startup.
  1199. These extra bindings are located in the users `C-c letter' map."
  1200.   :group 'reftex-miscellaneous-configurations
  1201.   :type '(boolean))
  1202.  
  1203. (defcustom reftex-plug-into-AUCTeX nil
  1204.   "*Plug-in flags for AUCTeX interface.
  1205. This variable is a list of 4 boolean flags.  When a flag is non-nil, it
  1206. means:
  1207.  
  1208.   Flag 1:  use `reftex-label'     as `LaTeX-label-function'.
  1209.   Flag 2:  use `reftex-arg-label' as `TeX-arg-label'
  1210.   Flag 3:  use `reftex-arg-ref'   as `TeX-arg-ref'
  1211.   Flag 4:  use `reftex-arg-cite'  as `TeX-arg-cite'
  1212.  
  1213. You may also set the variable itself to t or nil in order to turn all
  1214. plug-ins on or off, respectively.
  1215. \\<LaTeX-mode-map>`LaTeX-label-function' is the function used for label insertion when you
  1216. enter a new environment in AUCTeX with \\[LaTeX-environment].
  1217. The `TeX-arg-label' etc. functions are for entering macro arguments during
  1218. macro insertion with \\[TeX-insert-macro].
  1219. See the AUCTeX documentation for more information.
  1220. RefTeX uses `fset' to take over the function calls.  Changing the variable
  1221. may require a restart of Emacs in order to become effective."
  1222.   :group 'reftex-miscellaneous-configurations
  1223.   :type '(choice (const :tag "No plug-ins" nil)
  1224.                  (const :tag "All possible plug-ins" t)
  1225.                  (list
  1226.                   :tag "Individual choice"
  1227.                   :value (nil nil nil nil)
  1228.                   (boolean :tag "Use reftex-label     as LaTeX-label-function")
  1229.                   (boolean :tag "Use reftex-arg-label as TeX-arg-label       ")
  1230.                   (boolean :tag "Use reftex-arg-ref   as TeX-arg-ref         ")
  1231.                   (boolean :tag "Use reftex-arg-cite  as TeX-arg-cite        ")
  1232.                   )))
  1233.  
  1234. (defcustom reftex-use-fonts t
  1235.   "*Non-nil means, use fonts in label menu and on-the-fly help.
  1236. Font-lock must be loaded as well to actually get fontified display."
  1237.   :group 'reftex-miscellaneous-configurations
  1238.   :type '(boolean))
  1239.  
  1240. (defcustom reftex-auto-show-entry 'copy
  1241.   "*Non-nil means, do something when context in other window is hidden.
  1242. Some modes like `outline-mode' or `folding-mode' hide parts of buffers.
  1243. When RefTeX is asked to show context for a label definition, and the context
  1244. is invisible, it can unhide that section permanently (value t), or copy the
  1245. context to a temporary buffer (value 'copy)."
  1246.   :group 'reftex-miscellaneous-configurations
  1247.   :type '(radio :value copy
  1248.                 :indent 4
  1249.           (const :tag "Do nothing" nil)
  1250.           (const :tag "Unhide section permanently" t)
  1251.           (const :tag "Copy context to show" copy)))
  1252.  
  1253. (defcustom reftex-revisit-to-follow t
  1254.   "*Non-nil means, follow-mode will revisit files if necessary.
  1255. When nil, follow-mode will be suspended for stuff in unvisited files."
  1256.   :group 'reftex-miscellaneous-configurations
  1257.   :type '(boolean))
  1258.  
  1259. (defcustom reftex-load-hook nil
  1260.   "Hook which is being run when loading reftex.el."
  1261.   :group 'reftex-miscellaneous-configurations
  1262.   :type 'hook)
  1263.  
  1264. (defcustom reftex-mode-hook nil
  1265.   "Hook which is being run when turning on RefTeX mode."
  1266.   :group 'reftex-miscellaneous-configurations
  1267.   :type 'hook)
  1268.  
  1269. ;;; End of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1270.  
  1271. ;;;===========================================================================
  1272. ;;;
  1273. ;;; Define the formal stuff for a minor mode named RefTeX.
  1274. ;;;
  1275.  
  1276. (defconst reftex-version "RefTeX version 3.17"
  1277.   "Version string for RefTeX.")
  1278.  
  1279. (defvar reftex-mode nil
  1280.   "Determines if RefTeX minor mode is active.")
  1281. (make-variable-buffer-local 'reftex-mode)
  1282.  
  1283. (defvar reftex-mode-map (make-sparse-keymap)
  1284.   "Keymap for RefTeX minor mode.")
  1285.  
  1286. (defvar reftex-mode-menu nil)
  1287.  
  1288. ;;;###autoload
  1289. (defun turn-on-reftex ()
  1290.   "Turn on RefTeX minor mode."
  1291.   (reftex-mode t))
  1292.  
  1293. ;;;###autoload
  1294. (defun reftex-mode (&optional arg)
  1295.   "Minor mode with distinct support for \\label, \\ref and \\cite in LaTeX.
  1296.  
  1297. Labels can be created with `\\[reftex-label]' and referenced with `\\[reftex-reference]'.
  1298. When referencing, you get a menu with all labels of a given type and
  1299. context of the label definition.  The selected label is inserted as a
  1300. \\ref macro.
  1301.  
  1302. Citations can be made with `\\[reftex-citation]' which will use a regular expression
  1303. to pull out a *formatted* list of articles from your BibTeX
  1304. database.  The selected citation is inserted as a \\cite macro.
  1305.  
  1306. A Table of Contents of the entire (multifile) document with browsing
  1307. capabilities is available with `\\[reftex-toc]'.
  1308.  
  1309. Most command have help available on the fly.  This help is accessed by
  1310. pressing `?' to any prompt mentioning this feature.
  1311.  
  1312. Extensive documentation about RefTeX is in the file header of `reftex.el'.
  1313. You can view this information with `\\[reftex-show-commentary]'.
  1314.  
  1315. \\{reftex-mode-map}
  1316. Under X, these and other functions will also be available as `Ref' menu
  1317. on the menu bar.
  1318.  
  1319. ------------------------------------------------------------------------------"
  1320.  
  1321.   (interactive "P")
  1322.   (setq reftex-mode (not (or (and (null arg) reftex-mode)
  1323.                              (<= (prefix-numeric-value arg) 0))))
  1324.  
  1325.   ; Add or remove the menu, and run the hook
  1326.   (if reftex-mode
  1327.       (progn
  1328.         (easy-menu-add reftex-mode-menu)
  1329.         (reftex-plug-into-AUCTeX)
  1330.         (run-hooks 'reftex-mode-hook))
  1331.     (easy-menu-remove reftex-mode-menu)))
  1332.  
  1333. (or (assoc 'reftex-mode minor-mode-alist)
  1334.     (push '(reftex-mode " Ref") minor-mode-alist))
  1335.  
  1336. (or (assoc 'reftex-mode minor-mode-map-alist)
  1337.     (push (cons 'reftex-mode reftex-mode-map) minor-mode-map-alist))
  1338.  
  1339. ;;; ===========================================================================
  1340. ;;;
  1341. ;;; Silence warnings about variables in other packages.
  1342. (defvar TeX-master)
  1343. (defvar LaTeX-label-function)
  1344. (defvar tex-main-file)
  1345. (defvar outline-minor-mode)
  1346. (defvar font-lock-fontify-region-function)
  1347. (defvar font-lock-syntactic-keywords)
  1348.  
  1349. ;;; ===========================================================================
  1350. ;;;
  1351. ;;; Interfaces for other packages
  1352. ;;; -----------------------------
  1353. ;;;
  1354. ;;; AUCTeX
  1355. ;;; ------
  1356.  
  1357. (defun reftex-arg-label (optional &optional prompt definition)
  1358.   "Use `reftex-label' to create label.  Insert it with `TeX-argument-insert'.
  1359. This function is intended for AUCTeX macro support."
  1360.   (let ((label (reftex-label nil t)))
  1361.     (if (and definition (not (string-equal "" label)))
  1362.         (LaTeX-add-labels label))
  1363.     (TeX-argument-insert label optional optional)))
  1364.  
  1365. (defun reftex-arg-ref (optional &optional prompt definition)
  1366.   "Use `reftex-reference' to select label.  Insert with `TeX-argument-insert'.
  1367. This function is intended for AUCTeX macro support."
  1368.   (let ((label (reftex-reference nil t)))
  1369.     (if (and definition (not (string-equal "" label)))
  1370.         (LaTeX-add-labels label))
  1371.     (TeX-argument-insert label optional optional)))
  1372.  
  1373. (defun reftex-arg-cite (optional &optional prompt definition)
  1374.   "Use reftex-citation to select a key.  Insert with `TeX-argument-insert'.
  1375. This function is intended for AUCTeX macro support."
  1376.   (let ((key (reftex-citation t)))
  1377.     (TeX-argument-insert (or key "") optional optional)))
  1378.  
  1379. (defun reftex-plug-into-AUCTeX ()
  1380.   ;; Replace AUCTeX functions with RefTeX functions.
  1381.   ;; Which functions are replaced is controlled by the variable
  1382.   ;; `reftex-plug-into-AUCTeX'.
  1383.   (let ((flags
  1384.          (cond ((eq reftex-plug-into-AUCTeX t) '(t t t t))
  1385.                ((eq reftex-plug-into-AUCTeX nil) '(nil nil nil nil))
  1386.                (t reftex-plug-into-AUCTeX))))
  1387.  
  1388.     (and (nth 0 flags)
  1389.          (boundp 'LaTeX-label-function)
  1390.          (setq LaTeX-label-function 'reftex-label))
  1391.  
  1392.     (and (nth 1 flags)
  1393.          (fboundp 'TeX-arg-label)
  1394.          (fset 'TeX-arg-label 'reftex-arg-label))
  1395.  
  1396.     (and (nth 2 flags)
  1397.          (fboundp 'TeX-arg-ref)
  1398.          (fset 'TeX-arg-ref 'reftex-arg-ref))
  1399.  
  1400.     (and (nth 3 flags)
  1401.          (fboundp 'TeX-arg-cite)
  1402.          (fset 'TeX-arg-cite 'reftex-arg-cite))))
  1403.  
  1404.  
  1405. (defvar reftex-label-alist-external-add-ons nil
  1406.   "List of label alist entries added with reftex-add-to-label-alist.")
  1407.  
  1408. (defun reftex-add-to-label-alist (entry-list)
  1409.   "Add label environment descriptions to `reftex-label-alist-external-add-ons'.
  1410. The format of ENTRY-LIST is exactly like `reftex-label-alist'.  See there
  1411. for details.
  1412. This function makes it possible to support RefTeX from AUCTeX style files.
  1413. The entries in ENTRY-LIST will be processed after the user settings in
  1414. `reftex-label-alist', and before the defaults (specified in
  1415. `reftex-default-label-alist-entries').  Any changes made to
  1416. `reftex-label-alist-external-add-ons' will raise a flag to the effect that a
  1417. mode reset is done on the next occasion."
  1418.   (let (entry)
  1419.     (while entry-list
  1420.       (setq entry (car entry-list)
  1421.             entry-list (cdr entry-list))
  1422.       (unless (member entry reftex-label-alist-external-add-ons)
  1423.         (setq reftex-tables-dirty t)
  1424.         (push entry reftex-label-alist-external-add-ons)))))
  1425.  
  1426. ;;; ===========================================================================
  1427. ;;;
  1428. ;;; Multifile support
  1429. ;;;
  1430. ;;; Technical notes: Multifile works as follows: We keep just one list
  1431. ;;; of labels for each master file - this can save a lot of memory.
  1432. ;;; `reftex-master-index-list' is an alist which connects the true file name
  1433. ;;; of each master file with the symbols holding the information on that
  1434. ;;; document.  Each buffer has local variables which point to these symbols.
  1435.  
  1436. ;; List of variables which handle the multifile stuff.
  1437. ;; This list is used to tie, untie, and reset these symbols.
  1438. (defconst reftex-multifile-symbols
  1439.   '(reftex-docstruct-symbol))
  1440.  
  1441. ;; Alist connecting master file names with the corresponding lisp symbols.
  1442. (defvar reftex-master-index-list nil)
  1443.  
  1444. ;; Last index used for a master file.
  1445. (defvar reftex-multifile-index 0)
  1446.  
  1447. ;; Variable holding the symbol with the label list of the document.
  1448. (defvar reftex-docstruct-symbol nil)
  1449. (make-variable-buffer-local 'reftex-docstruct-symbol)
  1450.  
  1451. (defun reftex-next-multifile-index ()
  1452.   ;; Return the next free index for multifile symbols.
  1453.   (incf reftex-multifile-index))
  1454.  
  1455. (defun reftex-tie-multifile-symbols ()
  1456.   ;; Tie the buffer-local symbols to globals connected with the master file.
  1457.   ;; If the symbols for the current master file do not exist, they are created.
  1458.  
  1459.   (let* ((master (file-truename (reftex-TeX-master-file)))
  1460.          (index (assoc master reftex-master-index-list))
  1461.          (symlist reftex-multifile-symbols)
  1462.          (symbol nil)
  1463.          (symname nil)
  1464.          (newflag nil))
  1465.     ;; Find the correct index.
  1466.     (if index
  1467.         ;; symbols do exist
  1468.         (setq index (cdr index))
  1469.       ;; Get a new index and add info to the alist.
  1470.       (setq index (reftex-next-multifile-index)
  1471.             newflag t)
  1472.       (push (cons master index) reftex-master-index-list))
  1473.  
  1474.     ;; Get/create symbols and tie them.
  1475.     (while symlist
  1476.       (setq symbol (car symlist)
  1477.             symlist (cdr symlist)
  1478.             symname (symbol-name symbol))
  1479.       (set symbol (intern (concat symname "-" (int-to-string index))))
  1480.       (put (symbol-value symbol) ':master-index index)
  1481.       ;; Initialize if new symbols.
  1482.       (if newflag (set (symbol-value symbol) nil)))
  1483.  
  1484.     ;; Return t if the symbols did already exist, nil when we've made them.
  1485.     (not newflag)))
  1486.  
  1487. (defun reftex-untie-multifile-symbols ()
  1488.   ;; Remove ties from multifile symbols, so that next use makes new ones.
  1489.   (let ((symlist reftex-multifile-symbols)
  1490.         (symbol nil))
  1491.     (while symlist
  1492.       (setq symbol  (car symlist)
  1493.             symlist (cdr symlist))
  1494.       (set symbol nil))))
  1495.  
  1496. (defun reftex-TeX-master-file ()
  1497.   ;; Return the name of the master file associated with the current buffer.
  1498.   ;; When AUCTeX is loaded, we will use it's more sophisticated method.
  1499.   ;; We also support the default TeX and LaTeX modes by checking for a
  1500.   ;; variable tex-main-file.
  1501.   (let
  1502.       ((master
  1503.         (cond
  1504.          ((fboundp 'TeX-master-file) ; AUCTeX is loaded.  Use its mechanism.
  1505.           (TeX-master-file t))
  1506.          ((boundp 'TeX-master)       ; The variable is defined - lets use it.
  1507.           (cond
  1508.            ((eq TeX-master t)
  1509.             (buffer-file-name))
  1510.            ((eq TeX-master 'shared)
  1511.             (setq TeX-master (read-file-name "Master file: "
  1512.                                              nil nil t nil)))
  1513.            (TeX-master)
  1514.            (t
  1515.             (setq TeX-master (read-file-name "Master file: "
  1516.                                              nil nil t nil)))))
  1517.          ((boundp 'tex-main-file)
  1518.           ;; This is the variable from the default TeX modes.
  1519.           (cond
  1520.            ((stringp tex-main-file)
  1521.             ;; ok, this must be it
  1522.             tex-main-file)
  1523.            (t
  1524.             ;; In this case, the buffer is its own master.
  1525.             (buffer-file-name))))
  1526.          (t
  1527.           ;; Know nothing about master file.  Assume this is a master file.
  1528.           (buffer-file-name)))))
  1529.     (cond
  1530.      ((null master)
  1531.       (error "Need a filename for this buffer.  Please save it first."))
  1532.      ((or (file-exists-p master)
  1533.           (reftex-get-buffer-visiting master))
  1534.       ;; We either see the file, or have a buffer on it.  OK.
  1535.       )
  1536.      ((or (file-exists-p (concat master ".tex"))
  1537.           (reftex-get-buffer-visiting (concat master ".tex")))
  1538.       ;; Ahh, an extra .tex was missing...
  1539.       (setq master (concat master ".tex")))
  1540.      (t
  1541.       ;; Something is wrong here.  Throw an exception.
  1542.       (buffer-file-name)))
  1543. ;      (error "No such master file %s" master)))
  1544.     (expand-file-name master)))
  1545.  
  1546. (defun reftex-parse-one ()
  1547.   "Re-parse this file."
  1548.   (interactive)
  1549.   (let ((reftex-enable-partial-scans t))
  1550.     (reftex-access-scan-info '(4))))
  1551.  
  1552. (defun reftex-parse-all ()
  1553.   "Re-parse entire document."
  1554.   (interactive)
  1555.   (reftex-access-scan-info '(16)))
  1556.  
  1557. (defun reftex-all-document-files (&optional relative)
  1558.   ;; Return a list of all files belonging to the current document.
  1559.   ;; When RELATIVE is non-nil, give file names relative to directory
  1560.   ;; of master file.
  1561.   (let* ((all (symbol-value reftex-docstruct-symbol))
  1562.          (master-dir (file-name-directory (reftex-TeX-master-file)))
  1563.          (re (concat "\\`" (regexp-quote master-dir)))
  1564.         file-list tmp file)
  1565.     (while (setq tmp (assoc 'bof all))
  1566.       (setq file (nth 1 tmp)
  1567.             all (cdr (memq tmp all)))
  1568.       (and relative
  1569.            (string-match re file)
  1570.            (setq file (substring file (match-end 0))))
  1571.       (push file file-list))
  1572.     (nreverse file-list)))
  1573.  
  1574. (defun reftex-create-tags-file ()
  1575.   "Create TAGS file by running `etags' on the current document.
  1576. The TAGS file is also immediately visited with `visit-tags-table'."
  1577.   (interactive)
  1578.   (reftex-access-scan-info current-prefix-arg)
  1579.   (let* ((master (reftex-TeX-master-file))
  1580.          (files  (reftex-all-document-files))
  1581.          (cmd    (format "etags %s" (mapconcat 'identity files " "))))
  1582.     (save-excursion
  1583.       (set-buffer (reftex-get-buffer-visiting master))
  1584.       (message "Running etags to create TAGS file...")
  1585.       (shell-command cmd)
  1586.       (visit-tags-table "TAGS"))))
  1587.  
  1588. ;; History of grep commands.
  1589. (defvar reftex-grep-history nil)
  1590. (defvar reftex-grep-command "grep -n "
  1591.   "Last grep command used in \\[reftex-grep-document]; default for next grep.")
  1592.  
  1593. (defun reftex-grep-document (grep-cmd)
  1594.   "Run grep query through all files related to this document.
  1595. With prefix arg, force to rescan document.
  1596. This works also without an active TAGS table."
  1597.  
  1598.   (interactive
  1599.    (list (read-from-minibuffer "Run grep on document (like this): "
  1600.                                reftex-grep-command nil nil
  1601.                                'reftex-grep-history)))
  1602.   (reftex-access-scan-info current-prefix-arg)
  1603.   (let* ((files  (reftex-all-document-files t))
  1604.          (cmd    (format
  1605.                   "%s %s" grep-cmd
  1606.                   (mapconcat 'identity files " "))))
  1607.     (grep cmd)))
  1608.  
  1609. (defun reftex-search-document (&optional regexp)
  1610.   "Regexp search through all files of the current TeX document.
  1611. Starts always in the master file.  Stops when a match is found.
  1612. To continue searching for next match, use command \\[tags-loop-continue].
  1613. This works also without an active TAGS table."
  1614.   (interactive)
  1615.   (let ((default (reftex-this-word)))
  1616.     (unless regexp
  1617.       (setq regexp (read-string (format "Search regexp in document [%s]: "
  1618.                                         default))))
  1619.     (if (string= regexp "") (setq regexp (regexp-quote default)))
  1620.  
  1621.     (reftex-access-scan-info current-prefix-arg)
  1622.     (tags-search regexp (list 'reftex-all-document-files))))
  1623.  
  1624. (defun reftex-query-replace-document (&optional from to delimited)
  1625.   "Run a query-replace-regexp of FROM with TO over the entire TeX document.
  1626. Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
  1627. If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
  1628. with the command \\[tags-loop-continue].
  1629. This works also without an active TAGS table."
  1630.   (interactive)
  1631.   (let ((default (reftex-this-word)))
  1632.     (unless from
  1633.       (setq from (read-string (format "Replace regexp in document [%s]: "
  1634.                                       default)))
  1635.       (if (string= from "") (setq from (regexp-quote default))))
  1636.     (unless to
  1637.       (setq to (read-string (format "Replace regexp %s with: " from))))
  1638.     (reftex-access-scan-info current-prefix-arg)
  1639.     (tags-query-replace from to (or delimited current-prefix-arg)
  1640.                         (list 'reftex-all-document-files))))
  1641.  
  1642. (defun reftex-change-label (&optional from to)
  1643.   "Query replace FROM with TO in all \\label and \\ref commands.
  1644. Works on the entire multifile document.
  1645. If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
  1646. with the command \\[tags-loop-continue].
  1647. This works also without an active TAGS table."
  1648.   (interactive)
  1649.   (let ((default (reftex-this-word "-a-zA-Z0-9_*.:")))
  1650.     (unless from
  1651.       (setq from (read-string (format "Replace label globally [%s]: "
  1652.                                       default))))
  1653.     (if (string= from "") (setq from default))
  1654.     (unless to
  1655.       (setq to (read-string (format "Replace label %s with: "
  1656.                                     from))))
  1657.     (reftex-query-replace-document
  1658.      (concat "\\\\\\(label\\|[a-z]*ref\\){" (regexp-quote from) "}")
  1659.      (format "\\\\\\1{%s}" to))))
  1660.  
  1661. (defun reftex-save-all-document-buffers ()
  1662.   "Save all documents associated with the current document.
  1663. The function is useful after a global action like replacing or renumbering
  1664. labels."
  1665.   (interactive)
  1666.   (let ((files (reftex-all-document-files))
  1667.     file buffer)
  1668.     (save-excursion
  1669.       (while (setq file (pop files))
  1670.     (setq buffer (reftex-get-buffer-visiting file))
  1671.     (when buffer
  1672.       (set-buffer buffer)
  1673.       (save-buffer))))))
  1674.  
  1675. ;;; ===========================================================================
  1676. ;;;
  1677. ;;; Functions to create and reference automatic labels.
  1678.  
  1679. ;; The following constants are derived from `reftex-label-alist'.
  1680.  
  1681. ;; Prompt used for label type queries directed to the user.
  1682. (defconst reftex-type-query-prompt nil)
  1683.  
  1684. ;; Help string for label type queries.
  1685. (defconst reftex-type-query-help nil)
  1686.  
  1687. ;; Alist relating label type to reference format.
  1688. (defconst reftex-typekey-to-format-alist nil)
  1689.  
  1690. ;; Alist relating label type to label affix.
  1691. (defconst reftex-typekey-to-prefix-alist nil)
  1692.  
  1693. ;; Alist relating environments or macros to label type and context regexp.
  1694. (defconst reftex-env-or-mac-alist nil)
  1695.  
  1696. ;; List of macros carrying a label.
  1697. (defconst reftex-label-mac-list nil)
  1698.  
  1699. ;; List of environments carrying a label.
  1700. (defconst reftex-label-env-list nil)
  1701.  
  1702. ;; List of all typekey letters in use.
  1703. (defconst reftex-typekey-list nil)
  1704.  
  1705. ;; Alist relating magic words to a label type.
  1706. (defconst reftex-words-to-typekey-alist nil)
  1707.  
  1708. ;; The last list-of-labels entry used in a reference.
  1709. (defvar reftex-last-used-reference (list nil nil nil nil))
  1710.  
  1711. ;; The regular expression used to abbreviate words.
  1712. (defconst reftex-abbrev-regexp
  1713.   (concat
  1714.    "\\`\\("
  1715.    (make-string (nth 0 reftex-abbrev-parameters) ?.)
  1716.    "[" (nth 2 reftex-abbrev-parameters) "]*"
  1717.    "\\)"
  1718.    "[" (nth 3 reftex-abbrev-parameters) "]"
  1719.    (make-string (1- (nth 1 reftex-abbrev-parameters)) ?.)))
  1720.  
  1721. ;; Global variables used for communication between functions.
  1722. (defvar reftex-default-context-position nil)
  1723. (defvar reftex-location-start nil)
  1724. (defvar reftex-call-back-to-this-buffer nil)
  1725. (defvar reftex-active-toc nil)
  1726. (defvar reftex-tex-path nil)
  1727. (defvar reftex-bib-path nil)
  1728. (defvar reftex-prefix)
  1729.  
  1730. ;; List of buffers created temporarily for lookup, which should be killed.
  1731. (defvar reftex-buffers-to-kill nil)
  1732.  
  1733. ;; Regexp to find section statements.  Computed from reftex-section-levels.
  1734. (defvar reftex-section-regexp nil)
  1735. (defvar reftex-section-or-include-regexp nil)
  1736. (defvar reftex-everything-regexp nil)
  1737. (defvar reftex-find-label-regexp-format nil)
  1738. (defvar reftex-find-label-regexp-format2 nil)
  1739.  
  1740. ;; The parser functions ----------------------------------
  1741.  
  1742. (defvar reftex-memory nil
  1743.   "Memorizes old variable values to indicate changes in these variables.")
  1744.  
  1745. (defun reftex-access-scan-info (&optional rescan file)
  1746.   ;; Access the scanning info.  When the multifile symbols are not yet tied,
  1747.   ;; tie them.  When they are empty or RESCAN is non-nil, scan the document.
  1748.   ;; When FILE is non-nil, parse only from that file.
  1749.  
  1750.   ;; Reset the mode if we had changes to important variables.
  1751.   (when (or reftex-tables-dirty
  1752.         (not (eq reftex-label-alist (nth 0 reftex-memory)))
  1753.         (not (eq reftex-label-alist-external-add-ons
  1754.              (nth 1 reftex-memory)))
  1755.         (not (eq reftex-default-label-alist-entries
  1756.              (nth 2 reftex-memory))))
  1757.     (reftex-reset-mode))
  1758.  
  1759.   (if (eq reftex-docstruct-symbol nil)
  1760.       ;; Symbols are not yet tied: Tie them.
  1761.       (reftex-tie-multifile-symbols))
  1762.   
  1763.   (when (or (null (symbol-value reftex-docstruct-symbol))
  1764.         (member rescan '(t 1 (4) (16))))
  1765.     ;; The docstruct will change: Remove selection buffers.
  1766.     (save-excursion
  1767.       (reftex-erase-all-selection-buffers)))
  1768.  
  1769.   (if (and (null (symbol-value reftex-docstruct-symbol))
  1770.            reftex-save-parse-info)
  1771.       ;; Try to read the stuff from a file
  1772.       (reftex-access-parse-file 'read))
  1773.  
  1774.   (cond
  1775.    ((not (symbol-value reftex-docstruct-symbol))
  1776.     (reftex-do-parse 1 file))
  1777.    ((member rescan '(t 1 (4) (16)))
  1778.     (reftex-do-parse rescan file))))
  1779.  
  1780. (defun reftex-do-parse (rescan &optional file)
  1781.   ;; Do a rescan.  When allowed, do only a partial scan from FILE.
  1782.  
  1783.   ;; Normalize the rescan argument
  1784.   (setq rescan (cond ((eq rescan t) t)
  1785.                      ((eq rescan 1) 1)
  1786.                      ((equal rescan '(4)) t)
  1787.                      ((equal rescan '(16)) 1)
  1788.                      (t 1)))
  1789.  
  1790.   ;; Partial scans only when allowed
  1791.   (unless reftex-enable-partial-scans
  1792.     (setq rescan 1))
  1793.  
  1794.   ;; Do the scanning.
  1795.  
  1796.   (let* ((old-list (symbol-value reftex-docstruct-symbol))
  1797.          (master (reftex-TeX-master-file))
  1798.      (master-dir (file-name-as-directory (file-name-directory master)))
  1799.          (file (or file (buffer-file-name)))
  1800.          from-file appendix docstruct tmp)
  1801.  
  1802.     ;; Make sure replacement is really an option here
  1803.     (when (and (eq rescan t)
  1804.                (not (and (member (list 'bof file) old-list)
  1805.                          (member (list 'eof file) old-list))))
  1806.       (message "Scanning whole document (no file section %s)" file)
  1807.       (setq rescan 1))
  1808.     (when (string= file master)
  1809.       (message "Scanning whole document (%s is master)" file)
  1810.       (setq rescan 1))
  1811.  
  1812.     ;; From which file do we start?
  1813.     (setq from-file
  1814.           (cond ((eq rescan t) (or file master))
  1815.                 ((eq rescan 1) master)
  1816.                 (t (error "horrible!!"))))
  1817.  
  1818.     ;; Find active toc entry and initialize section-numbers
  1819.     (setq reftex-active-toc (reftex-last-assoc-before-elt
  1820.                  'toc (list 'bof from-file) old-list)
  1821.       appendix (reftex-last-assoc-before-elt
  1822.             'appendix (list 'bof from-file) old-list))
  1823.  
  1824.     (reftex-init-section-numbers reftex-active-toc appendix)
  1825.  
  1826.     (if (eq rescan 1)
  1827.         (message "Scanning entire document...")
  1828.       (message "Scanning document from %s..." from-file))
  1829.  
  1830.     (save-window-excursion
  1831.       (save-excursion
  1832.         (unwind-protect
  1833.             (setq docstruct
  1834.                   (reftex-parse-from-file
  1835.                    from-file docstruct master-dir))
  1836.           (reftex-kill-temporary-buffers))))
  1837.  
  1838.     (message "Scanning document... done")
  1839.  
  1840.     ;; Turn the list around.
  1841.     (setq docstruct (nreverse docstruct))
  1842.  
  1843.     ;; Set or insert
  1844.     (setq docstruct (reftex-replace-label-list-segment
  1845.                      old-list docstruct (eq rescan 1)))
  1846.  
  1847.     ;; Add all missing information
  1848.     (unless (assq 'label-numbers docstruct)
  1849.       (push (cons 'label-numbers nil) docstruct))
  1850.     (unless (assq 'master-dir docstruct)
  1851.       (push (cons 'master-dir master-dir) docstruct))
  1852.     (let* ((bof1 (memq (assq 'bof docstruct) docstruct))
  1853.            (bof2 (assq 'bof (cdr bof1)))
  1854.            (is-multi (not (not (and bof1 bof2))))
  1855.            (entry (or (assq 'is-multi docstruct)
  1856.                       (car (push (list 'is-multi is-multi) docstruct)))))
  1857.       (setcdr entry (cons is-multi nil)))
  1858.     (unless (assq 'xr docstruct)
  1859.       (let* ((allxr (reftex-all-assq 'xr-doc docstruct))
  1860.          (alist (mapcar
  1861.              (function
  1862.               (lambda (x) 
  1863.             (if (setq tmp (reftex-find-tex-file (nth 2 x)
  1864.                                 master-dir))
  1865.                 (cons (nth 1 x) tmp)
  1866.               (message "Can't find external document %s"
  1867.                    (nth 2 x))
  1868.               nil)))
  1869.             allxr))
  1870.          (alist (delete nil alist))
  1871.          (allprefix (delete nil (mapcar 'car alist)))
  1872.          (regexp (if allprefix
  1873.              (concat "\\`\\(" 
  1874.                  (mapconcat 'identity allprefix "\\|")
  1875.                  "\\)")
  1876.                "\\\\\\\\\\\\")))   ; this will never match
  1877.     (push (list 'xr alist regexp) docstruct)))
  1878.  
  1879.     (set reftex-docstruct-symbol docstruct)
  1880.  
  1881.     ;; Save the parsing information into a file?
  1882.     (if reftex-save-parse-info
  1883.         (reftex-access-parse-file 'write))))
  1884.  
  1885. (defun reftex-is-multi ()
  1886.   ;; Tell if this is a multifile document.  When not sure, say yes.
  1887.   (let ((entry (assq 'is-multi (symbol-value reftex-docstruct-symbol))))
  1888.     (if entry
  1889.         (nth 1 entry)
  1890.       t)))
  1891.  
  1892. (defun reftex-parse-from-file (file docstruct master-dir)
  1893.   ;; Scan the buffer for labels and save them in a list.
  1894.   (let ((regexp reftex-everything-regexp)
  1895.         (bound 0)
  1896.         file-found tmp include-file
  1897.         (level 1)
  1898.         (highest-level 100)
  1899.         toc-entry next-buf)
  1900.  
  1901.     (catch 'exit
  1902.       (setq file-found (reftex-find-tex-file file master-dir))
  1903.       (unless file-found
  1904.         (push (list 'file-error file) docstruct)
  1905.         (throw 'exit nil))
  1906.  
  1907.       (save-excursion
  1908.  
  1909.         (message "Scanning file %s" file)
  1910.         (set-buffer
  1911.          (setq next-buf
  1912.                (reftex-get-file-buffer-force
  1913.                 file-found
  1914.                 (not (eq t reftex-keep-temporary-buffers)))))
  1915.  
  1916.         ;; Begin of file mark
  1917.         (setq file (buffer-file-name))
  1918.         (push (list 'bof file) docstruct)
  1919.  
  1920.         (save-excursion
  1921.           (save-restriction
  1922.             (widen)
  1923.             (goto-char 1)
  1924.  
  1925.             (while (re-search-forward regexp nil t)
  1926.  
  1927.               (cond
  1928.  
  1929.                ((match-end 1)
  1930.                ;; It is a label
  1931.                 (push (reftex-label-info (reftex-match-string 1) file bound)
  1932.                       docstruct))
  1933.  
  1934.                ((match-end 3)
  1935.                 ;; It is a section
  1936.                 (setq bound (point))
  1937.  
  1938.                 ;; Insert in List
  1939.                 (setq toc-entry (reftex-section-info file))
  1940.                 (setq level (nth 5 toc-entry))
  1941.                 (setq highest-level (min highest-level level))
  1942.                 (if (= level highest-level)
  1943.                     (message
  1944.                      "Scanning %s %s ..."
  1945.                      (car (nth level reftex-section-levels))
  1946.                      (nth 6 toc-entry)))
  1947.  
  1948.                 (push toc-entry docstruct)
  1949.                 (setq reftex-active-toc toc-entry))
  1950.  
  1951.                ((match-end 7)
  1952.                 ;; It's an include or input
  1953.         (setq include-file (reftex-match-string 7))
  1954.         (if (delq nil (mapcar 
  1955.                    (lambda (x) (string-match x include-file))
  1956.                    reftex-no-include-regexps))
  1957.             (progn
  1958.               ;; Ignore the file
  1959.               (push (list 'bof include-file) docstruct)
  1960.               (push (list 'eof include-file) docstruct))
  1961.           ;; Parse it
  1962.           (setq docstruct
  1963.             (reftex-parse-from-file
  1964.              include-file
  1965.              docstruct master-dir))))
  1966.  
  1967.            ((match-end 9)
  1968.         ;; Appendix starts here
  1969.         (reftex-init-section-numbers nil t)
  1970.         (push (cons 'appendix t) docstruct))
  1971.  
  1972.                ((match-end 10)
  1973.                 ;; A macro with label
  1974.                 (save-excursion
  1975.                   (let* ((mac (reftex-match-string 10))
  1976.              (label (progn (goto-char (match-end 10))
  1977.                        (save-match-data
  1978.                      (reftex-no-props
  1979.                       (reftex-nth-arg-wrapper
  1980.                        mac)))))
  1981.                          (entry (progn (goto-char (match-end 0))
  1982.                                        (reftex-label-info
  1983.                     label file bound mac))))
  1984.                     (push entry docstruct))))
  1985.                (t (error "This should not happen (reftex-parse-from-file)")))
  1986.               )
  1987.  
  1988.  
  1989.             ;; Find bibliography statement
  1990.             (when (setq tmp (reftex-locate-bibliography-files master-dir))
  1991.               (push (cons 'bib tmp) docstruct))
  1992.  
  1993.         (goto-char 1)
  1994.         (when (re-search-forward 
  1995.            "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
  1996.           (push (cons 'thebib file) docstruct))
  1997.            
  1998.         ;; Find external document specifications
  1999.         (goto-char 1)
  2000.         (while (re-search-forward "[\n\r][ \t]*\\\\externaldocument\\(\\[\\([^]]*\\)\\]\\)?{\\([^}]+\\)}" nil t)
  2001.           (push (list 'xr-doc (reftex-match-string 2)
  2002.               (reftex-match-string 3))
  2003.             docstruct))
  2004.  
  2005.             ;; End of file mark
  2006.             (push (list 'eof file) docstruct))))
  2007.  
  2008.       ;; Kill the scanned buffer
  2009.       (reftex-kill-temporary-buffers next-buf))
  2010.  
  2011.     ;; Return the list
  2012.     docstruct))
  2013.  
  2014. (defun reftex-locate-bibliography-files (master-dir)
  2015.   ;; Scan buffer for bibliography macro and return file list.
  2016.   (let (file-list)
  2017.     (save-excursion
  2018.       (goto-char (point-min))
  2019.       (if (re-search-forward
  2020.            "\\(\\`\\|[\n\r]\\)[ \t]*\\\\bibliography{[ \t]*\\([^}]+\\)" nil t)
  2021.           (setq file-list
  2022.                 (mapcar (function (lambda (x) (concat x ".bib")))
  2023.                         (reftex-delete-list
  2024.                          reftex-bibfile-ignore-list
  2025.                          (split-string
  2026.                           (reftex-match-string 2)
  2027.                           "[ \t\n\r]*,[ \t\n\r]*")))))
  2028.       (delete nil
  2029.           (mapcar 
  2030.            (function 
  2031.         (lambda (file)
  2032.           (reftex-find-bib-file file master-dir)))
  2033.            file-list)))))
  2034.   
  2035. (defun reftex-last-assoc-before-elt (key elt list)
  2036.   ;; Find the last association of KEY in LIST before or at ELT
  2037.   ;; ELT is found in LIST with equal, not eq.
  2038.   ;; Returns nil when either KEY or elt are not found in LIST.
  2039.   ;; On success, returns the association.
  2040.   (let* ((elt (car (member elt list))) ass last-ass)
  2041.  
  2042.     (while (and (setq ass (assoc key list))
  2043.                 (setq list (memq ass list))
  2044.                 (memq elt list))
  2045.       (setq last-ass ass
  2046.             list (cdr list)))
  2047.     last-ass))
  2048.  
  2049. (defun reftex-replace-label-list-segment (old insert &optional entirely)
  2050.   ;; Replace the segment in OLD which corresponds to INSERT.
  2051.   ;; Works with side effects, directly changes old.
  2052.   ;; If entirely is t, just return INSERT.
  2053.   ;; This function also makes sure the old toc markers do not point anywhere.
  2054.  
  2055.   (cond
  2056.    (entirely
  2057.     (reftex-silence-toc-markers old (length old))
  2058.     insert)
  2059.    (t (let* ((new old)
  2060.              (file (nth 1 (car insert)))
  2061.              (eof-list (member (list 'eof file) old))
  2062.              (bof-list (member (list 'bof file) old))
  2063.              n)
  2064.         (if (not (and bof-list eof-list))
  2065.             (error "Cannot splice")
  2066.           ;; Splice
  2067.           (reftex-silence-toc-markers bof-list (- (length bof-list)
  2068.                                                   (length eof-list)))
  2069.           (setq n (- (length old) (length bof-list)))
  2070.           (setcdr (nthcdr n new) (cdr insert))
  2071.           (setcdr (nthcdr (1- (length new)) new) (cdr eof-list)))
  2072.         new))))
  2073.  
  2074. (defun reftex-silence-toc-markers (list n)
  2075.   ;; Set all markers in list to nil
  2076.   (while (and list (> (decf n) -1))
  2077.     (and (eq (car (car list)) 'toc)
  2078.          (markerp (nth 4 (car list)))
  2079.          (set-marker (nth 4 (car list)) nil))
  2080.     (pop list)))
  2081.  
  2082. (defun reftex-access-parse-file (action)
  2083.   (let* ((list (symbol-value reftex-docstruct-symbol))
  2084.          (master (reftex-TeX-master-file))
  2085.      (enable-local-variables nil)
  2086.          (file (if (string-match "\\.[a-zA-Z]+\\'" master)
  2087.                    (concat (substring master 0 (match-beginning 0)) ".rel")
  2088.                  (concat master ".rel"))))
  2089.     (cond
  2090.      ((eq action 'readable)
  2091.       (file-readable-p file))
  2092.      ((eq action 'restore)
  2093.       (if (eq reftex-docstruct-symbol nil)
  2094.           ;; Symbols are not yet tied: Tie them.
  2095.           (reftex-tie-multifile-symbols))
  2096.       (if (file-exists-p file)
  2097.           ;; load the file and return t for success
  2098.           (progn (load-file file) t)
  2099.         ;; throw an exception
  2100.         (error "No restore file %s" file)))
  2101.      ((eq action 'read)
  2102.       (if (file-exists-p file)
  2103.           ;; load the file and return t for success
  2104.           (progn (load-file file) t)
  2105.         ;; return nil for failure, but no exception
  2106.         nil))
  2107.      (t
  2108.       (save-excursion
  2109.         (if (file-writable-p file)
  2110.             (progn
  2111.               (message "Writing parse file %s" (abbreviate-file-name file))
  2112.               (find-file file)
  2113.               (erase-buffer)
  2114.               (insert (format ";; RefTeX parse info file\n"))
  2115.               (insert (format ";; File: %s\n" master))
  2116.               (insert (format ";; Date: %s\n"
  2117.                               (format-time-string "%D %T"
  2118.                                                   (current-time))))
  2119.               (insert (format ";; User: %s (%s)\n\n"
  2120.                               (user-login-name) (user-full-name)))
  2121.               (insert "(set reftex-docstruct-symbol '(\n\n")
  2122.               (let ((standard-output (current-buffer)))
  2123.                 (mapcar
  2124.                  (function
  2125.                   (lambda (x)
  2126.                     (cond ((eq (car x) 'toc)
  2127.                            ;; A toc entry. Do not save the marker.
  2128.                            ;; Save the markers  position at position 8
  2129.                            (print (list 'toc "toc" (nth 2 x) (nth 3 x)
  2130.                                         nil (nth 5 x) (nth 6 x) (nth 7 x)
  2131.                                         (or (and (markerp (nth 4 x))
  2132.                                                  (marker-position (nth 4 x)))
  2133.                                             (nth 8 x)))))
  2134.                           (t (print x)))))
  2135.                  list))
  2136.               (insert "))")
  2137.               (save-buffer 0)
  2138.               (kill-buffer (current-buffer)))
  2139.           (error "Cannot write to file %s" file)))
  2140.       t))))
  2141.  
  2142. ;; Creating labels --------------
  2143.  
  2144. (defun reftex-label (&optional environment no-insert)
  2145.   "Insert a unique label.  Return the label.
  2146. If ENVIRONMENT is given, don't bother to find out yourself.
  2147. If NO-INSERT is non-nil, do not insert label into buffer.
  2148. With prefix arg, force to rescan document first.
  2149. When you are prompted to enter or confirm a label, and you reply with
  2150. just the prefix or an empty string, no label at all will be inserted.
  2151. A new label is also recorded into the label list.
  2152. This function is controlled by the settings of reftex-insert-label-flags."
  2153.  
  2154.   (interactive)
  2155.  
  2156.   ;; Ensure access to scanning info and rescan buffer if prefix are is '(4).
  2157.   (reftex-access-scan-info current-prefix-arg)
  2158.  
  2159.   ;; Find out what kind of environment this is and abort if necessary.
  2160.   (if (or (not environment)
  2161.           (not (assoc environment reftex-env-or-mac-alist)))
  2162.       (setq environment (reftex-label-location)))
  2163.   (unless environment
  2164.     (error "Can't figure out what kind of label should be inserted"))
  2165.  
  2166.   ;; Ok, go ahead.
  2167.   (catch 'exit
  2168.     (let* ((entry (assoc environment reftex-env-or-mac-alist))
  2169.        (typekey (nth 1 entry))
  2170.        (format (nth 3 entry))
  2171.        label prefix valid default force-prompt rescan-is-useful)
  2172.       (when (and (eq (string-to-char environment) ?\\)
  2173.          (nth 5 entry)
  2174.          (memq (preceding-char) '(?\[ ?\{)))
  2175.     (setq format "%s"))
  2176.  
  2177.       (setq prefix (or (cdr (assoc typekey reftex-typekey-to-prefix-alist))
  2178.                (concat typekey "-")))
  2179.       ;; Replace any escapes in the prefix
  2180.       (setq prefix (reftex-replace-prefix-escapes prefix))
  2181.  
  2182.       ;; Make a default label.
  2183.       (cond
  2184.  
  2185.        ((reftex-typekey-check typekey (nth 0 reftex-insert-label-flags))
  2186.     ;; Derive a label from context.
  2187.     (setq reftex-active-toc (reftex-last-assoc-before-elt
  2188.                  'toc (car (reftex-where-am-I))
  2189.                  (symbol-value reftex-docstruct-symbol)))
  2190.     (setq default (reftex-no-props
  2191.                (nth 2 (reftex-label-info " " nil nil t))))
  2192.     ;; Catch the cases where the is actually no context available.
  2193.     (if (or (string-match "NO MATCH FOR CONTEXT REGEXP" default)
  2194.         (string-match "ILLEGAL VALUE OF PARSE" default)
  2195.         (string-match "SECTION HEADING NOT FOUND" default)
  2196.         (string-match "HOOK ERROR" default)
  2197.         (string-match "^[ \t]*$" default))
  2198.         (setq default prefix
  2199.           force-prompt t)    ; need to prompt
  2200.       (setq default (concat prefix (reftex-string-to-label default)))
  2201.  
  2202.       ;; Make it unique.
  2203.       (setq default (reftex-uniquify-label default nil "-"))))
  2204.  
  2205.        ((reftex-typekey-check typekey (nth 1 reftex-insert-label-flags))
  2206.     ;; Minimal default: the user will be prompted.
  2207.     (setq default prefix))
  2208.  
  2209.        (t
  2210.     ;; Make an automatic label.
  2211.     (setq default (reftex-uniquify-label prefix t))))
  2212.  
  2213.       ;; Should we ask the user?
  2214.       (if (or (reftex-typekey-check typekey
  2215.                     (nth 1 reftex-insert-label-flags)) ; prompt
  2216.           force-prompt)
  2217.  
  2218.       (while (not valid)
  2219.         ;; iterate until we get a legal label
  2220.  
  2221.         (setq label (read-string
  2222.              (if (string= format "%s") "Naked Label: " "Label: ")
  2223.              default))
  2224.  
  2225.         ;; Lets make sure that this is a legal label
  2226.         (cond
  2227.  
  2228.          ((string-match (concat "\\`\\(" (regexp-quote prefix)
  2229.                     "\\)?[ \t]*\\'")
  2230.                 label)
  2231.           ;; No label at all, please
  2232.           (message "No label inserted.")
  2233.           (throw 'exit nil))
  2234.  
  2235.          ;; Test if label contains strange characters
  2236.          ((string-match reftex-label-illegal-re label)
  2237.           (message "Label \"%s\" contains illegal characters" label)
  2238.           (ding)
  2239.           (sit-for 2))
  2240.  
  2241.          ;; Look it up in the label list
  2242.          ((setq entry (assoc label
  2243.                  (symbol-value reftex-docstruct-symbol)))
  2244.           (ding)
  2245.           (if (y-or-n-p 
  2246.            (format "Label '%s' exists. Use anyway? " label))
  2247.           (setq valid t)))
  2248.  
  2249.          ;; Label is ok
  2250.          (t
  2251.           (setq valid t))))
  2252.     (setq label default))
  2253.  
  2254.       ;; Insert the label into the label list
  2255.       (let* ((here-I-am-info (reftex-where-am-I))
  2256.          (here-I-am (car here-I-am-info))
  2257.          (note (if (cdr here-I-am-info)
  2258.                ""
  2259.              "POSITION UNCERTAIN.  RESCAN TO FIX."))
  2260.          (file (buffer-file-name))
  2261.          (text nil)
  2262.          (tail (memq here-I-am (symbol-value reftex-docstruct-symbol))))
  2263.  
  2264.     (or (cdr here-I-am-info) (setq rescan-is-useful t))
  2265.  
  2266.     (if tail
  2267.         (setcdr tail (cons (list label typekey text file note)
  2268.                    (cdr tail)))))
  2269.  
  2270.       ;; Insert the label into the buffer
  2271.       (unless no-insert
  2272.     (insert
  2273.      (if reftex-format-label-function
  2274.          (funcall reftex-format-label-function label format)
  2275.        (format format label))))
  2276.  
  2277.       ;; Delete the corresponding selection buffers to force update on next use.
  2278.       (when reftex-auto-update-selection-buffers
  2279.     (reftex-erase-buffer (reftex-make-selection-buffer-name typekey))
  2280.     (reftex-erase-buffer (reftex-make-selection-buffer-name " ")))
  2281.  
  2282.       (when (and rescan-is-useful reftex-allow-automatic-rescan)
  2283.     (reftex-parse-one))
  2284.  
  2285.       ;; return value of the function is the label
  2286.       label)))
  2287.  
  2288. (defun reftex-string-to-label (string)
  2289.   ;; Convert a string (a sentence) to a label.
  2290.   ;;
  2291.   ;; Uses reftex-derive-label-parameters and reftex-abbrev-parameters
  2292.   ;;
  2293.  
  2294.   (let* ((words0 (split-string string "[- \t\n\r]+"))
  2295.          (ignore-words (nth 5 reftex-derive-label-parameters))
  2296.          words word)
  2297.  
  2298.     ;; remove words from the ignore list or with funny characters
  2299.     (while (setq word (pop words0))
  2300.       (cond
  2301.        ((member (downcase word) ignore-words))
  2302.        ((string-match reftex-label-illegal-re word)
  2303.         (when (nth 2 reftex-derive-label-parameters)
  2304.           (while (string-match reftex-label-illegal-re word)
  2305.             (setq word (replace-match "" nil nil word)))
  2306.           (push word words)))
  2307.        (t
  2308.         (push word words))))
  2309.     (setq words (nreverse words))
  2310.  
  2311.     ;; restrict number of words
  2312.     (if (> (length words) (nth 0 reftex-derive-label-parameters))
  2313.         (setcdr (nthcdr (1- (nth 0 reftex-derive-label-parameters)) words) nil))
  2314.  
  2315.     ;; First, try to use all words
  2316.     (setq string (mapconcat 'identity words
  2317.                             (nth 4 reftex-derive-label-parameters)))
  2318.  
  2319.     ;; Abbreviate words if enforced by user settings or string length
  2320.     (if (or (eq t (nth 3 reftex-derive-label-parameters))
  2321.             (and (nth 3 reftex-derive-label-parameters)
  2322.                  (> (length string) (nth 1 reftex-derive-label-parameters))))
  2323.         (setq words
  2324.               (mapcar
  2325.            (function
  2326.         (lambda (w) (if (string-match reftex-abbrev-regexp w)
  2327.                 (match-string 1 w)
  2328.                   w)))
  2329.                words)
  2330.               string (mapconcat 'identity words
  2331.                                 (nth 4 reftex-derive-label-parameters))))
  2332.  
  2333.     ;; Shorten if still to long
  2334.     (setq string
  2335.           (if (> (length string) (nth 1 reftex-derive-label-parameters))
  2336.               (substring string 0 (nth 1 reftex-derive-label-parameters))
  2337.             string))
  2338.  
  2339.     ;; Delete the final punctuation, if any
  2340.     (if (string-match "[^a-zA-Z0-9]+\\'" string)
  2341.         (setq string (replace-match "" nil nil string)))
  2342.     string))
  2343.  
  2344. (defun reftex-replace-prefix-escapes (prefix)
  2345.   ;; Replace %escapes in a label prefix
  2346.   (save-match-data
  2347.     (let (letter (num 0) replace)
  2348.       (while (string-match "\\%\\([a-zA-Z]\\)" prefix num)
  2349.         (setq letter (match-string 1 prefix))
  2350.         (setq replace
  2351.               (cond
  2352.                ((equal letter "f")
  2353.                 (file-name-sans-extension
  2354.                  (file-name-nondirectory (buffer-file-name))))
  2355.                ((equal letter "F")
  2356.                 (let ((masterdir (file-name-directory (reftex-TeX-master-file)))
  2357.                       (file (file-name-sans-extension (buffer-file-name))))
  2358.                   (if (string-match (concat "\\`" (regexp-quote masterdir))
  2359.                                     file)
  2360.                       (substring file (length masterdir))
  2361.                     file)))
  2362.                ((equal letter "u")
  2363.                 (or (user-login-name) ""))
  2364.                (t "")))
  2365.         (setq num (1- (+ (match-beginning 1) (length replace)))
  2366.               prefix (replace-match replace nil nil prefix)))
  2367.       prefix)))
  2368.  
  2369. (defun reftex-label-location (&optional bound)
  2370.   ;; Return the environment or macro which determines the label type at point.
  2371.   ;; If optional BOUND is an integer, limit backward searches to that point.
  2372.  
  2373.   (let* ((loc1 (reftex-what-macro reftex-label-mac-list bound))
  2374.          (loc2 (reftex-what-environment reftex-label-env-list bound))
  2375.          (p1 (or (cdr loc1) 0))
  2376.          (p2 (or (cdr loc2) 0)))
  2377.  
  2378.     (setq reftex-location-start (max p1 p2))
  2379.     (if (>= p1 p2)
  2380.         (progn
  2381.           (setq reftex-default-context-position (+ p1 (length (car loc1))))
  2382.           (or (car loc1) "section"))
  2383.       (setq reftex-default-context-position (+ p2 8 (length (car loc2))))
  2384.       (or (car loc2) "section"))))
  2385.  
  2386. (defun reftex-uniquify-label (label &optional force separator)
  2387.   ;; Make label unique by appending a number.
  2388.   ;; Optional FORCE means, force appending a number, even if label is unique.
  2389.   ;; Optional SEPARATOR is a string to stick between label and number.
  2390.  
  2391.   ;; Ensure access to scanning info
  2392.   (reftex-access-scan-info)
  2393.  
  2394.   (cond
  2395.    ((and (not force)
  2396.          (not (assoc label (symbol-value reftex-docstruct-symbol))))
  2397.     label)
  2398.    (t
  2399.     (let* ((label-numbers (assq 'label-numbers
  2400.                                 (symbol-value reftex-docstruct-symbol)))
  2401.            (label-numbers-alist (cdr label-numbers))
  2402.            (cell (or (assoc label label-numbers-alist)
  2403.                      (car (setcdr label-numbers
  2404.                                   (cons (cons label 0)
  2405.                                         label-numbers-alist)))))
  2406.            (num (1+ (cdr cell)))
  2407.            (sep (or separator "")))
  2408.       (while (assoc (concat label sep (int-to-string num))
  2409.                     (symbol-value reftex-docstruct-symbol))
  2410.         (incf num))
  2411.       (setcdr cell num)
  2412.       (concat label sep (int-to-string num))))))
  2413.  
  2414. ;; Help string for the reference label menu
  2415. (defconst reftex-select-label-prompt
  2416.   "Select: [n]ext [p]revious [r]escan [ ]context e[x]tern [q]uit RET [?]HELP+more")
  2417.  
  2418. (defconst reftex-select-label-help
  2419.   " n / p      Go to next/previous label (Cursor motion works as well)
  2420.  C-c C-n/p  Go to next/previous section heading.
  2421.  b / l      Jump back to previous selection / Reuse last referenced label
  2422.  C-s / C-r  Search forward/backward.  Use repeated C-s/C-r as in isearch.
  2423.  g / s      Update menu      / Switch label type
  2424.  r / R      Reparse document / Reparse entire document
  2425.  x          Switch to label menu of external document (with LaTeX package `xr')
  2426.  t i c # %  Toggle: [i]ncl. file borders, [t]able of contents,  [c]ontext
  2427.                     [#] label counters,   [%] labels in comments
  2428.  SPC / f    Show full context in other window / Toggle follow mode
  2429.  v / e      Toggle \\ref <-> \\vref  / Recursive Edit into other window
  2430.  TAB        Enter a label with completion
  2431.  q / RET    Quit without accepting label / Accept current label")
  2432.  
  2433. (defvar reftex-select-label-map nil
  2434.   "Keymap used for *RefTeX Select* buffer, when selecting a label.
  2435. This keymap can be used to configure the label selection process which is
  2436. started with the command \\[reftex-reference].")
  2437.  
  2438. (defun reftex-reference (&optional type no-insert cut)
  2439.   "Make a LaTeX reference.  Look only for labels of a certain TYPE.
  2440. With prefix arg, force to rescan buffer for labels.  This should only be
  2441. necessary if you have recently entered labels yourself without using
  2442. reftex-label.  Rescanning of the buffer can also be requested from the
  2443. label selection menu.
  2444. The function returns the selected label or nil.
  2445. If NO-INSERT is non-nil, do not insert \\ref command, just return label.
  2446. When called with 2 C-u prefix args, disable magic word recognition."
  2447.  
  2448.   (interactive)
  2449.  
  2450.   ;; check for active recursive edits
  2451.   (reftex-check-recursive-edit)
  2452.  
  2453.   ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
  2454.   (reftex-access-scan-info current-prefix-arg)
  2455.  
  2456.   (unless type
  2457.     ;; guess type from context
  2458.     (if (and reftex-guess-label-type
  2459.              (setq type (reftex-guess-label-type)))
  2460.     (setq cut (cdr type)
  2461.           type (car type))
  2462.       (setq type (reftex-query-label-type))))
  2463.  
  2464.   (let* ((varioref (if (reftex-typekey-check 
  2465.             type reftex-vref-is-default)
  2466.                "\\vref" "\\ref"))
  2467.      (form "\\ref{%s}")
  2468.      label pair)
  2469.  
  2470.     ;; Have the user select a label
  2471.     (setq pair (save-excursion
  2472.          (reftex-offer-label-menu type)))
  2473.     (setq label (car pair)
  2474.       type  (cdr pair)
  2475.       form (or (cdr (assoc type reftex-typekey-to-format-alist))
  2476.            form))
  2477.  
  2478.     (if (and label
  2479.              (not no-insert))
  2480.         (progn
  2481.       (if cut (backward-delete-char cut))
  2482.  
  2483.       ;; remove ~ if we do already have a space
  2484.       (when (and (= ?~ (string-to-char form))
  2485.              (= ?\  (preceding-char)))
  2486.         (setq form (substring form 1)))
  2487.       ;; do we need to switch from \ref to \vref?
  2488.       (when (string= varioref "\\vref")
  2489.         (while (string-match "\\\\ref{" form)
  2490.           (setq form (replace-match "\\vref{" t t form))))
  2491.           ;; ok, insert the reference
  2492.       (insert
  2493.        (if reftex-format-ref-function
  2494.            (funcall reftex-format-ref-function label form)
  2495.          (format form label label)))
  2496.           (message ""))
  2497.       (message "Quit"))
  2498.     ;; return the label
  2499.     label))
  2500.  
  2501. (defun reftex-guess-label-type ()
  2502.   (let ((words reftex-words-to-typekey-alist)
  2503.     (case-fold-search t)
  2504.     (bound (max (point-min) (- (point) 35)))
  2505.     matched    cell)
  2506.     (save-excursion
  2507.       (while (and (setq cell (pop words))
  2508.           (not (setq matched 
  2509.                  (re-search-backward (car cell) bound t))))))
  2510.     (if matched
  2511.     (cons (cdr cell) (- (match-end 0) (match-end 1)))
  2512.       nil)))
  2513.  
  2514. (defun reftex-offer-label-menu (typekey)
  2515.   ;; Offer a menu with the appropriate labels.  Return (label . typekey).
  2516.   (let* ((buf (current-buffer))
  2517.      (xr-data (assq 'xr (symbol-value reftex-docstruct-symbol)))
  2518.      (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
  2519.      (xr-index 0)
  2520.          (here-I-am (car (reftex-where-am-I)))
  2521.      (here-I-am1 here-I-am)
  2522.          (toc (reftex-typekey-check typekey reftex-label-menu-flags 0))
  2523.          (files (reftex-typekey-check typekey reftex-label-menu-flags 7))
  2524.          (context (not (reftex-typekey-check
  2525.                         typekey reftex-label-menu-flags 3)))
  2526.          (counter (reftex-typekey-check
  2527.                    typekey reftex-label-menu-flags 2))
  2528.          (follow  (reftex-typekey-check
  2529.                    typekey reftex-label-menu-flags 4))
  2530.          (commented (nth 5 reftex-label-menu-flags))
  2531.          (match-everywhere (reftex-typekey-check
  2532.                             typekey reftex-label-menu-flags 6))
  2533.      (prefix "")
  2534.      selection-buffers
  2535.          offset rtn key data last-data entry)
  2536.  
  2537.     (setq entry (cons nil nil))
  2538.  
  2539.     ;; The following unwind-protect kills temporary buffers after use
  2540.     (unwind-protect
  2541.         (catch 'exit
  2542.           (while t
  2543.             (save-window-excursion
  2544.           (delete-other-windows)
  2545.           (setq reftex-call-back-to-this-buffer buf)
  2546.           (if reftex-use-multiple-selection-buffers
  2547.           (switch-to-buffer-other-window
  2548.            (save-excursion
  2549.              (set-buffer buf)
  2550.              (reftex-make-selection-buffer-name typekey)))
  2551.         (switch-to-buffer-other-window "*RefTeX Select*")
  2552.         (erase-buffer))
  2553.           (add-to-list 'selection-buffers (current-buffer))
  2554.               (setq truncate-lines t)
  2555.           (setq mode-line-format
  2556.             (list "----  " 'mode-line-buffer-identification
  2557.               "   " 'varioref
  2558.               "   " (abbreviate-file-name
  2559.                  (buffer-file-name buf))
  2560.               " -%-"))
  2561.           (cond
  2562.            ((= 0 (buffer-size))
  2563.         (setq offset (reftex-make-and-insert-label-list
  2564.                   typekey buf toc files context counter commented
  2565.                   (or here-I-am offset) prefix)))
  2566.            (here-I-am
  2567.         (setq offset (reftex-get-offset buf here-I-am typekey)))
  2568.            (t (setq offset t)))
  2569.           (setq offset (or offset t))
  2570.  
  2571.               (setq here-I-am nil) ; turn off determination of offset
  2572.               (setq rtn
  2573.                     (reftex-select-item
  2574.                      reftex-select-label-prompt
  2575.                      reftex-select-label-help
  2576.              reftex-select-label-map
  2577.                      offset
  2578.                      'reftex-select-label-callback follow
  2579.                      match-everywhere))
  2580.               (setq key       (car rtn)
  2581.                     data      (nth 1 rtn)
  2582.                     last-data (nth 2 rtn)
  2583.             offset    t)
  2584.               (unless key (throw 'exit nil))
  2585.               (cond
  2586.            ((eq key ?g)
  2587.         ;; update buffer
  2588.         (erase-buffer))
  2589.                ((or (eq key ?r)
  2590.                     (eq key ?R))
  2591.                 ;; rescan buffer
  2592.         (erase-buffer)
  2593.                 (reftex-parse-document buf last-data key))
  2594.                ((eq key ?c)
  2595.                 ;; toggle context mode
  2596.         (erase-buffer)
  2597.                 (setq context (not context)))
  2598.                ((eq key ?s)
  2599.                 ;; switch type
  2600.         (setq here-I-am here-I-am1)
  2601.                 (setq typekey (reftex-query-label-type)))
  2602.                ((eq key ?t)
  2603.                 ;; toggle table of contents display
  2604.         (erase-buffer)
  2605.                 (setq toc (not toc)))
  2606.                ((eq key ?i)
  2607.                 ;; toggle display of included file borders
  2608.         (erase-buffer)
  2609.                 (setq files (not files)))
  2610.                ((eq key ?#)
  2611.                 ;; toggle counter display
  2612.         (erase-buffer)
  2613.                 (setq counter (not counter)))
  2614.                ((eq key ?%)
  2615.                 ;; toggle display of commented labels
  2616.         (erase-buffer)
  2617.                 (setq commented (not commented)))
  2618.                ((eq key ?l)
  2619.                 ;; reuse the last referenced label again
  2620.                 (setq entry reftex-last-used-reference)
  2621.                 (throw 'exit t))
  2622.            ((eq key ?x)
  2623.         ;; select an external document
  2624.         (setq xr-index (reftex-select-external-document
  2625.                 xr-alist xr-index))
  2626.         (setq buf (or (reftex-get-file-buffer-force
  2627.                    (cdr (nth xr-index xr-alist)))
  2628.                   (error "Cannot switch document"))
  2629.               prefix (or (car (nth xr-index xr-alist)) ""))
  2630.         (set-buffer buf)
  2631.         (reftex-access-scan-info))
  2632.            ((stringp key)
  2633.         (setq entry 
  2634.               (or (assoc key (symbol-value reftex-docstruct-symbol))
  2635.               (list key typekey)))
  2636.         (throw 'exit t))
  2637.                (t
  2638.                 (set-buffer buf)
  2639.                 (if data
  2640.                     (progn
  2641.                       (setq entry data)
  2642.                       (setq reftex-last-used-reference entry))
  2643.                   (setq entry nil))
  2644.                 (throw 'exit t))))))
  2645.       (mapcar (function (lambda (buf) 
  2646.               (and (buffer-live-p buf)
  2647.                    (bury-buffer buf))))                       
  2648.           selection-buffers)
  2649.       (reftex-kill-buffer "*RefTeX Context Copy*")
  2650.       (reftex-kill-temporary-buffers))
  2651.     (cons (if (nth 0 entry) (concat prefix (nth 0 entry)) nil)
  2652.       (nth 1 entry))))
  2653.  
  2654. (defun reftex-select-external-document (xr-alist xr-index)
  2655.   ;; Return index of an external document.
  2656.   (let* ((len (length xr-alist)) (highest (1- (+ ?0 len)))
  2657.      (prompt (format "[%c-%c] Select      SPC/DEL: Scroll      TAB: Read prefix with completion" ?0 highest))
  2658.      key prefix)
  2659.     (cond
  2660.      ((= len 1)
  2661.       (message "No external documents available")
  2662.       (ding) 0)
  2663.      ((= len 2)
  2664.       (- 1 xr-index))
  2665.      (t
  2666.       (save-excursion
  2667.     (save-window-excursion
  2668.       (let* ((length (apply 'max (mapcar 
  2669.                       (lambda(x) (length (car x))) xr-alist)))
  2670.          (fmt (format " [%%c]  %%-%ds  %%s\n" length))
  2671.          (n (1- ?0)))
  2672.         (with-output-to-temp-buffer "*RefTeX Select*"
  2673.           (princ "SELECT EXTERNAL DOCUMENT\n------------------------\n")
  2674.           (princ
  2675.            (mapconcat
  2676.         (function
  2677.          (lambda (x) 
  2678.            (format fmt (incf n) (or (car x) "")
  2679.                (abbreviate-file-name (cdr x)))))
  2680.         xr-alist ""))))
  2681.       (reftex-enlarge-to-fit "*RefTeX Select*")
  2682.       (select-window (get-buffer-window "*RefTeX Select*"))
  2683.       (setq truncate-lines t)
  2684.       (catch 'exit
  2685.         (while t
  2686.           (princ prompt)
  2687.           (setq key (read-char-exclusive))
  2688.           (cond
  2689.            ((= key ?\C-?) (condition-case nil (scroll-down) (error nil)))
  2690.            ((= key ?\ )   (condition-case nil (scroll-up) (error nil)))
  2691.            ((and (>= key ?0) (<= key highest))
  2692.         (throw 'exit (- key ?0)))
  2693.            ((= key ?\C-i)
  2694.         (setq prefix (completing-read "Prefix: " xr-alist nil t))
  2695.         (throw 'exit (- len (length (memq (assoc prefix xr-alist)
  2696.                           xr-alist)))))
  2697.            (t (error "Illegal document selection [%c]" key)))))))))))
  2698.  
  2699. (defun reftex-make-selection-buffer-name (type &optional index)
  2700.   ;; Make unique name for a selection buffer.
  2701.   (format "*RefTeX[%s][%d]*" 
  2702.       type (or index (get reftex-docstruct-symbol ':master-index) 0)))
  2703.  
  2704. (defun reftex-get-offset (buf here-am-I typekey)
  2705.   ;; Find the correct offset data, like make-and-insert would, but faster.
  2706.   (save-excursion
  2707.     (set-buffer buf)
  2708.     (reftex-access-scan-info)
  2709.     (let* ((rest (memq here-am-I (symbol-value reftex-docstruct-symbol)))
  2710.        entry)
  2711.       (while (and (setq entry (pop rest))
  2712.           (not (and (stringp (car entry))
  2713.                 (equal typekey (nth 1 entry))))))
  2714.       entry)))
  2715.                   
  2716. (defun reftex-make-and-insert-label-list
  2717.   (typekey0 buf toc files context counter show-commented here-I-am xr-prefix)
  2718.   ;; Insert a menu of all labels in buffer BUF into current buffer.
  2719.   ;; Return the data property of the entry corresponding to HERE-I-AM.
  2720.   (let* ((font (reftex-use-fonts))
  2721.          (cnt 0)
  2722.          (index -1)
  2723.          (toc-indent " ")
  2724.          (label-indent
  2725.           (concat "> "
  2726.                   (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
  2727.          (context-indent
  2728.           (concat ".   "
  2729.                   (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
  2730.          all cell text label typekey note comment master-dir-re
  2731.          offset from to docstruct-symbol)
  2732.  
  2733.     (message "Creating Selection Buffer...")
  2734.  
  2735.     ;; Pop to buffer buf to get the correct buffer-local variables
  2736.     (save-excursion
  2737.       (set-buffer buf)
  2738.  
  2739.       ;; Ensure access to scanning info
  2740.       (reftex-access-scan-info)
  2741.  
  2742.       (setq docstruct-symbol reftex-docstruct-symbol
  2743.         all (symbol-value reftex-docstruct-symbol)
  2744.             reftex-active-toc nil
  2745.             master-dir-re
  2746.             (concat "\\`" (regexp-quote
  2747.                            (file-name-directory (reftex-TeX-master-file))))))
  2748.  
  2749.     (set (make-local-variable 'reftex-docstruct-symbol) docstruct-symbol)
  2750.     (set (make-local-variable 'reftex-prefix)
  2751.      (cdr (assoc typekey0 reftex-typekey-to-prefix-alist)))
  2752.     (if (equal reftex-prefix " ") (setq reftex-prefix nil))
  2753.  
  2754.     ;; Walk the docstruct and insert the appropriate stuff
  2755.     (while (setq cell (pop all))
  2756.  
  2757.       (incf index)
  2758.       (setq from (point))
  2759.  
  2760.       (if (eq cell here-I-am) (setq offset 'attention))
  2761.  
  2762.       (cond
  2763.  
  2764.        ((memq (car cell) '(bib thebib label-numbers appendix
  2765.                    master-dir is-multi xr xr-doc)))
  2766.        ;; These are currently ignored
  2767.  
  2768.        ((memq (car cell) '(bof eof file-error))
  2769.         ;; Beginning or end of a file
  2770.         (when files
  2771.           (insert
  2772.            " File " (if (string-match master-dir-re (nth 1 cell))
  2773.                    (substring (nth 1 cell) (match-end 0))
  2774.                  (nth 1 cell))
  2775.            (cond ((eq (car cell) 'bof) " starts here\n")
  2776.                  ((eq (car cell) 'eof) " ends here\n")
  2777.                  ((eq (car cell) 'file-error) " was not found\n")))
  2778.           (when font
  2779.             (put-text-property from (point)
  2780.                                'face 'font-lock-function-name-face))))
  2781.  
  2782.        ((eq (car cell) 'toc)
  2783.         ;; a table of contents entry
  2784.         (when toc
  2785.           (setq reftex-active-toc cell)
  2786.           (insert (concat toc-indent (nth 2 cell) "\n"))))
  2787.  
  2788.        ((stringp (car cell))
  2789.         ;; a label
  2790.         (when (null (nth 2 cell))
  2791.           ;; No context yet.  Quick update.
  2792.       (setcdr cell (cdr (reftex-label-info-update cell))))
  2793.  
  2794.         (setq label   (car cell)
  2795.               typekey (nth 1 cell)
  2796.               text    (nth 2 cell)
  2797.               note    (nth 4 cell)
  2798.               comment (get-text-property 0 'in-comment text))
  2799.  
  2800.         (when (and (or (string= typekey typekey0) (string= typekey0 " "))
  2801.                    (or show-commented (null comment)))
  2802.  
  2803.           ;; Yes we want this one
  2804.           (incf cnt)
  2805.       (if (eq offset 'attention) (setq offset cell))
  2806.  
  2807.       (setq label (concat xr-prefix label))
  2808.           (when comment (setq label (concat "% " label)))
  2809.           (insert label-indent label)
  2810.           (when font
  2811.             (put-text-property
  2812.              (- (point) (length label)) (point)
  2813.              'face (if comment
  2814.                        'font-lock-comment-face
  2815.                      'font-lock-reference-face)))
  2816.  
  2817.           (insert (if counter (format " (%d) " cnt) "")
  2818.                   (if comment " LABEL IS COMMENTED OUT " "")
  2819.                   (if note (concat "  " note) "")
  2820.                   "\n")
  2821.           (setq to (point))
  2822.  
  2823.           (when context
  2824.             (insert context-indent text "\n")
  2825.             (setq to (point)))
  2826.           (put-text-property from to ':data cell)
  2827.           (goto-char to)))))
  2828.  
  2829.     (when (reftex-refontify)
  2830.       (reftex-fontify-select-label-buffer))
  2831.     offset))
  2832.  
  2833. (defun reftex-parse-document (&optional buffer data key)
  2834.   "Rescan the document."
  2835.   (interactive)
  2836.   (save-window-excursion
  2837.     (save-excursion
  2838.       (if buffer
  2839.           (if (not (bufferp buffer))
  2840.               (error "No such buffer %s" (buffer-name buffer))
  2841.             (set-buffer buffer)))
  2842.       (let ((arg (if (eq key ?R) '(16) '(4)))
  2843.             (file (nth 3 data)))
  2844.         (reftex-access-scan-info arg file)))))
  2845.  
  2846. (defun reftex-query-label-type ()
  2847.   ;; Ask for label type
  2848.   (message reftex-type-query-prompt)
  2849.   (let ((key (read-char)))
  2850.     (when (eq key ?\?)
  2851.       (save-window-excursion
  2852.         (with-output-to-temp-buffer "*RefTeX Help*"
  2853.           (princ reftex-type-query-help))
  2854.     (reftex-enlarge-to-fit "*RefTeX Help*")
  2855.         (setq key (read-char))
  2856.         (kill-buffer "*RefTeX Help*")))
  2857.     (unless (member (char-to-string key) reftex-typekey-list)
  2858.       (error "No such label type: %s" (char-to-string key)))
  2859.     (char-to-string key)))
  2860.  
  2861. ;; Variable holding the vector with section numbers
  2862. (defvar reftex-section-numbers [0 0 0 0 0 0 0 0])
  2863.  
  2864. (defun reftex-section-info (file)
  2865.   ;; Return a section entry for the current match.
  2866.   ;; Carefull: This function expects the match-data to be still in place!
  2867.   (let* ((marker (set-marker (make-marker) (1- (match-beginning 3))))
  2868.          (macro (reftex-match-string 3))
  2869.          (star (= ?* (char-after (match-end 3))))
  2870.          (level (cdr (assoc macro reftex-section-levels)))
  2871.          (section-number (reftex-section-number level star))
  2872.          (text1 (save-match-data (save-excursion (reftex-context-substring))))
  2873.          (literal (buffer-substring-no-properties
  2874.                    (1- (match-beginning 3))
  2875.                    (min (point-max) (+ (match-end 0) (length text1) 1))))
  2876.      ;; Literal can be too short since text1 too short. No big problem. 
  2877.          (text (reftex-nicify-text text1)))
  2878.  
  2879.     ;; Add section number and indentation
  2880.     (setq text
  2881.           (concat
  2882.            (make-string (* reftex-level-indent level) ?\ )
  2883.            (if (nth 1 reftex-label-menu-flags) ; section number flag
  2884.                (concat section-number " "))
  2885.            text))
  2886.     ;; Fontify
  2887.     (if (reftex-use-fonts)
  2888.         (put-text-property 0 (length text)
  2889.                            'face 'font-lock-comment-face text))
  2890.     (list 'toc "toc" text file marker level section-number
  2891.           literal (marker-position marker))))
  2892.  
  2893. (defun reftex-label-info-update (cell)
  2894.   ;; Update information about just one label in a different file.
  2895.   ;; CELL contains the old info list
  2896.   (let* ((label   (nth 0 cell))
  2897.          (typekey (nth 1 cell))
  2898.          ;; (text    (nth 2 cell))
  2899.          (file    (nth 3 cell))
  2900.          (note    (nth 4 cell))
  2901.          (buf (reftex-get-file-buffer-force
  2902.                file (not (eq t reftex-keep-temporary-buffers)))))
  2903.     (if (not buf)
  2904.         (list label typekey "" file "LOST LABEL.  RESCAN TO FIX.")
  2905.       (save-excursion
  2906.         (set-buffer buf)
  2907.         (save-restriction
  2908.           (widen)
  2909.           (goto-char 1)
  2910.  
  2911.           (if (or (re-search-forward
  2912.            (format reftex-find-label-regexp-format
  2913.                (regexp-quote label)) nil t)
  2914.           (re-search-forward
  2915.            (format reftex-find-label-regexp-format2
  2916.                (regexp-quote label)) nil t))
  2917.  
  2918.               (progn
  2919.                 (backward-char 1)
  2920.                 (append (reftex-label-info label file) (list note)))
  2921.             (list label typekey "" file "LOST LABEL.  RESCAN TO FIX.")))))))
  2922.  
  2923. (defun reftex-label-info (label &optional file bound derive env-or-mac)
  2924.   ;; Return info list on LABEL at point.
  2925.   (let* ((env-or-mac (or env-or-mac (reftex-label-location bound)))
  2926.          (typekey (nth 1 (assoc env-or-mac reftex-env-or-mac-alist)))
  2927.          (file (or file (buffer-file-name)))
  2928.          (parse (if (reftex-typekey-check
  2929.                      typekey reftex-use-text-after-label-as-context)
  2930.                     nil
  2931.                   (nth 2 (assoc env-or-mac reftex-env-or-mac-alist))))
  2932.          (text (reftex-short-context env-or-mac parse reftex-location-start
  2933.                                      derive)))
  2934.     (if (reftex-in-comment)
  2935.         (put-text-property 0 1 'in-comment t text))
  2936.     (list label typekey text file)))
  2937.  
  2938. (defun reftex-in-comment ()
  2939.   (save-excursion
  2940.     (skip-chars-backward "^%\n\r")
  2941.     (eq (preceding-char) ?%)))
  2942.  
  2943. (defun reftex-short-context (env parse &optional bound derive)
  2944.   ;; Get about one line of useful context for the label definition at point.
  2945.  
  2946.   (if (consp parse)
  2947.       (setq parse (if derive (cdr parse) (car parse))))
  2948.  
  2949.   (reftex-nicify-text
  2950.  
  2951.    (cond
  2952.  
  2953.     ((null parse)
  2954.      (save-excursion
  2955.        (reftex-context-substring)))
  2956.  
  2957.     ((eq parse t)
  2958.      (if (string= env "section")
  2959.          ;; special treatment for section labels
  2960.          (save-excursion
  2961.            (if (and (re-search-backward reftex-section-or-include-regexp
  2962.                                         (point-min) t)
  2963.                     (match-end 2))
  2964.                (progn
  2965.                  (goto-char (match-end 0))
  2966.                  (reftex-context-substring))
  2967.              (if reftex-active-toc
  2968.                  (progn
  2969.                    (string-match "{\\([^}]*\\)" (nth 7 reftex-active-toc))
  2970.                    (match-string 1 (nth 7 reftex-active-toc)))
  2971.                "SECTION HEADING NOT FOUND")))
  2972.        (save-excursion
  2973.      (goto-char reftex-default-context-position)
  2974.      (unless (eq (string-to-char env) ?\\)
  2975.        (reftex-move-over-touching-args))
  2976.          (reftex-context-substring))))
  2977.  
  2978.     ((stringp parse)
  2979.      (save-excursion
  2980.        (if (re-search-backward parse bound t)
  2981.            (progn
  2982.              (goto-char (match-end 0))
  2983.              (reftex-context-substring))
  2984.          "NO MATCH FOR CONTEXT REGEXP")))
  2985.  
  2986.     ((integerp parse)
  2987.      (or (save-excursion
  2988.            (goto-char reftex-default-context-position)
  2989.            (reftex-nth-arg
  2990.             parse
  2991.             (nth 6 (assoc env reftex-env-or-mac-alist))))
  2992.          ""))
  2993.  
  2994.     ((fboundp parse)
  2995.      ;; A hook function.  Call it.
  2996.      (save-excursion
  2997.        (condition-case error-var
  2998.            (funcall parse env)
  2999.          (error (format "HOOK ERROR: %s" (cdr error-var))))))
  3000.     (t
  3001.      "ILLEGAL VALUE OF PARSE"))))
  3002.  
  3003. (defun reftex-where-am-I ()
  3004.   ;; Return the docstruct entry above point.  Actually returns a cons
  3005.   ;; cell in which the cdr is a flag indicating if the information is
  3006.   ;; exact (t) or approximate (nil).
  3007.  
  3008.   (let ((docstruct (symbol-value reftex-docstruct-symbol))
  3009.         (cnt 0) rtn
  3010.         found)
  3011.     (save-excursion
  3012.       (while (not rtn)
  3013.         (incf cnt)
  3014.         (setq found (re-search-backward reftex-everything-regexp nil t))
  3015.         (setq rtn
  3016.               (cond
  3017.                ((not found)
  3018.                 ;; no match
  3019.                 (or
  3020.                  (car (member (list 'bof (buffer-file-name)) docstruct))
  3021.                  (not (setq cnt 2))
  3022.                  (assq 'bof docstruct)  ;; for safety reasons
  3023.                  'corrupted))
  3024.                ((match-end 1)
  3025.                 ;; Label
  3026.                 (assoc (reftex-match-string 1)
  3027.                        (symbol-value reftex-docstruct-symbol)))
  3028.                ((match-end 3)
  3029.                 ;; Section
  3030.                 (goto-char (1- (match-beginning 3)))
  3031.                 (let* ((list (member (list 'bof (buffer-file-name))
  3032.                                      docstruct))
  3033.                        (endelt (car (member (list 'eof (buffer-file-name))
  3034.                                             list)))
  3035.                        rtn1)
  3036.                   (while (and list (not (eq endelt (car list))))
  3037.                     (if (and (eq (car (car list)) 'toc)
  3038.                              (string= (buffer-file-name)
  3039.                                       (nth 3 (car list))))
  3040.                         (cond
  3041.                          ((equal (point)
  3042.                                  (or (and (markerp (nth 4 (car list)))
  3043.                                           (marker-position (nth 4 (car list))))
  3044.                                      (nth 8 (car list))))
  3045.                           ;; Fits with marker position or recorded position
  3046.                           (setq rtn1 (car list) list nil))
  3047.                          ((looking-at (reftex-make-regexp-allow-for-ctrl-m
  3048.                                        (nth 7 (car list))))
  3049.                           ;; Same title
  3050.                           (setq rtn1 (car list) list nil cnt 2))))
  3051.                     (pop list))
  3052.                   rtn1))
  3053.                ((match-end 7)
  3054.                 ;; Input or include...
  3055.                 (car
  3056.                  (member (list 'eof (reftex-find-tex-file
  3057.                                      (reftex-match-string 7)
  3058.                       (cdr (assq 'master-dir docstruct))))
  3059.                          docstruct)))
  3060.            ((match-end 9)
  3061.         (assq 'appendix (symbol-value reftex-docstruct-symbol)))
  3062.                ((match-end 10)
  3063.                 (save-excursion
  3064.                   (goto-char (match-end 10))
  3065.                   (assoc (reftex-no-props
  3066.                           (reftex-nth-arg-wrapper
  3067.                            (reftex-match-string 10)))
  3068.                          (symbol-value reftex-docstruct-symbol))))
  3069.                (t
  3070.                 (error "This should not happen (reftex-where-am-I)"))))))
  3071.     (cons rtn (eq cnt 1))))
  3072.  
  3073. (defun reftex-parse-args (macro)
  3074.   ;; Return a list of macro name, nargs, arg-nr which is label and a list of
  3075.   ;; optional argument indices.
  3076.   (if (string-match "[[{]\\*?[]}]" macro)
  3077.       (progn
  3078.         (let ((must-match (substring macro 0 (match-beginning 0)))
  3079.               (args (substring macro (match-beginning 0)))
  3080.               opt-list nlabel (cnt 0))
  3081.           (while (string-match "\\`[[{]\\(\\*\\)?[]}]" args)
  3082.             (incf cnt)
  3083.             (when (eq ?\[ (string-to-char args))
  3084.               (push cnt opt-list))
  3085.             (when (and (match-end 1)
  3086.                (not nlabel))
  3087.           (setq nlabel cnt))
  3088.             (setq args (substring args (match-end 0))))
  3089.           (list must-match cnt nlabel opt-list)))
  3090.     nil))
  3091.  
  3092. (defsubst reftex-move-to-next-arg (&optional ignore)
  3093.   ;; Assuming that we are at the end of a macro name or a macro argument,
  3094.   ;; move forward to the opening parenthesis of the next argument.
  3095.   ;; This function understands the splitting of macros over several lines
  3096.   ;; in TeX.
  3097.   (cond
  3098.    ;; Just to be quick:
  3099.    ((memq (following-char) '(?\[ ?\{)))
  3100.    ;; Do a search
  3101.    ((looking-at "[ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*[[{]")
  3102.     (goto-char (1- (match-end 0)))
  3103.     t)
  3104.    (t nil)))
  3105.  
  3106. (defsubst reftex-move-to-previous-arg (&optional bound)
  3107.   ;; Assuming that we are in front of a macro argument,
  3108.   ;; move backward to the closing parenthesis of the previous argument.
  3109.   ;; This function understands the splitting of macros over several lines
  3110.   ;; in TeX.
  3111.   (cond
  3112.    ;; Just to be quick:
  3113.    ((memq (preceding-char) '(?\] ?\})))
  3114.    ;; Do a search
  3115.    ((re-search-backward
  3116.      "[]}][ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*\\=" bound t)
  3117.     (goto-char (1+ (match-beginning 0)))
  3118.     t)
  3119.    (t nil)))
  3120.  
  3121. (defun reftex-nth-arg-wrapper (key)
  3122.   (let ((entry (assoc key reftex-env-or-mac-alist)))
  3123.     (reftex-nth-arg (nth 5 entry) (nth 6 entry))))
  3124.  
  3125. (defun reftex-nth-arg (n &optional opt-args)
  3126.   ;; Return the nth following {} or [] parentheses content.
  3127.   ;; OPT-ARGS is a list of argument numbers which are optional.
  3128.  
  3129.   ;; If we are sitting at a macro start, skip to end of macro name.
  3130.   (and (eq (following-char) ?\\) (skip-chars-forward "a-zA-Z*\\\\"))
  3131.  
  3132.   (if (= n 1000)
  3133.       ;; Special case:  Skip all touching arguments
  3134.       (progn
  3135.     (reftex-move-over-touching-args)
  3136.     (reftex-context-substring))
  3137.  
  3138.     ;; Do the real thing.
  3139.     (let ((cnt 1))
  3140.       
  3141.       (when (reftex-move-to-next-arg)
  3142.     
  3143.     (while (< cnt n)
  3144.       (while (and (member cnt opt-args)
  3145.               (eq (following-char) ?\{))
  3146.         (incf cnt))
  3147.       (when (< cnt n)
  3148.         (unless (and (condition-case nil
  3149.                  (or (forward-list 1) t)
  3150.                (error nil))
  3151.              (reftex-move-to-next-arg)
  3152.              (incf cnt))
  3153.           (setq cnt 1000))))
  3154.  
  3155.     (while (and (memq cnt opt-args)
  3156.             (eq (following-char) ?\{))
  3157.       (incf cnt)))
  3158.       (if (and (= n cnt)
  3159.            (> (skip-chars-forward "{\\[") 0))
  3160.       (reftex-context-substring)
  3161.     nil))))
  3162.  
  3163. (defun reftex-move-over-touching-args ()
  3164.   (condition-case nil
  3165.       (while (memq (following-char) '(?\[ ?\{))
  3166.     (forward-list 1))
  3167.     (error nil)))  
  3168.  
  3169. (defun reftex-context-substring ()
  3170.   ;; Return up to 100 chars from point
  3171.   ;; When point is just after a { or [, limit string to matching parenthesis
  3172.   (cond
  3173.    ((or (= (preceding-char) ?\{)
  3174.         (= (preceding-char) ?\[))
  3175.     ;; Inside a list - get only the list.
  3176.     (buffer-substring-no-properties
  3177.      (point)
  3178.      (min (reftex-fp 150)
  3179.           (point-max)
  3180.           (condition-case nil
  3181.               (progn
  3182.                 (up-list 1)
  3183.                 (1- (point)))
  3184.             (error (point-max))))))
  3185.    (t
  3186.     ;; no list - just grab 100 characters
  3187.     (buffer-substring-no-properties (point) (min (reftex-fp 150) (point-max))))))
  3188.  
  3189. (defun reftex-init-section-numbers (&optional toc-entry appendix)
  3190.   ;; Initialize the section numbers with zeros or with what is found
  3191.   ;; in the toc entry.
  3192.   (let* ((level  (or (nth 5 toc-entry) -1))
  3193.          (numbers (nreverse (split-string (or (nth 6 toc-entry) "") "\\.")))
  3194.          (depth (1- (length reftex-section-numbers)))
  3195.          (i depth) number-string)
  3196.     (while (>= i 0)
  3197.       (if (> i level)
  3198.           (aset reftex-section-numbers i 0)
  3199.     (setq number-string (or (car numbers) "0"))
  3200.     (if (string-match "\\`[A-Z]\\'" number-string)
  3201.         (aset reftex-section-numbers i
  3202.           (- (string-to-char number-string) ?A -1))
  3203.         (aset reftex-section-numbers i (string-to-int number-string)))
  3204.         (pop numbers))
  3205.       (decf i)))
  3206.   (put 'reftex-section-numbers 'appendix appendix))
  3207.  
  3208. (defun reftex-section-number (&optional level star)
  3209.   ;; Return a string with the current section number.
  3210.   ;; When LEVEL is non-nil, increase section numbers on that level.
  3211.   (let* ((depth (1- (length reftex-section-numbers))) idx n (string "")
  3212.      (appendix (get 'reftex-section-numbers 'appendix)))
  3213.     (when level
  3214.       (when (and (> level -1) (not star))
  3215.         (aset reftex-section-numbers 
  3216.           level (1+ (aref reftex-section-numbers level))))
  3217.       (setq idx (1+ level))
  3218.       (while (<= idx depth)
  3219.         (aset reftex-section-numbers idx 0)
  3220.         (incf idx)))
  3221.     (setq idx 0)
  3222.     (while (<= idx depth)
  3223.       (setq n (aref reftex-section-numbers idx))
  3224.       (setq string (concat string (if (not (string= string "")) "." "")
  3225.                            (int-to-string n)))
  3226.       (incf idx))
  3227.     (save-match-data
  3228.       (if (string-match "\\`\\([@0]\\.\\)+" string)
  3229.           (setq string (replace-match "" nil nil string)))
  3230.       (if (string-match "\\(\\.0\\)+\\'" string)
  3231.           (setq string (replace-match "" nil nil string)))
  3232.       (if (and appendix
  3233.            (string-match "\\`[0-9]+" string))
  3234.       (setq string (concat (char-to-string (1- (+ ?A (string-to-int (match-string 0 string))))) (substring string (match-end 0))))))
  3235.            
  3236.     (if star
  3237.         (concat (make-string (1- (length string)) ?\ ) "*")
  3238.       string)))
  3239.  
  3240. (defun reftex-select-label-callback (data forward no-revisit)
  3241.   ;; Callback function called from the label selection in order to
  3242.   ;; show context in another window
  3243.   (let* ((this-window (selected-window))
  3244.          label file buffer re found)
  3245.     ;; pop to original buffer in order to get correct variables
  3246.     (catch 'exit
  3247.       (setq label (nth 0 data)
  3248.         file  (nth 3 data))
  3249.  
  3250.       ;; goto the file in another window
  3251.       (setq buffer 
  3252.         (if no-revisit
  3253.         (get-file-buffer file)
  3254.           (reftex-get-file-buffer-force
  3255.            file (not reftex-keep-temporary-buffers))))
  3256.       (if buffer
  3257.           ;; good - the file is available
  3258.           (switch-to-buffer-other-window buffer)
  3259.         ;; we have got a problem here.  The file does not exist.
  3260.         ;; Let' get out of here..
  3261.         ;; (ding)
  3262.         (throw 'exit nil))
  3263.  
  3264.       ;; search for that label
  3265.       (setq re (format reftex-find-label-regexp-format (regexp-quote label)))
  3266.       (setq found
  3267.         (if forward
  3268.         (re-search-forward re nil t)
  3269.           (re-search-backward re nil t)))
  3270.       (unless found
  3271.         (goto-char (point-min))
  3272.     (unless (re-search-forward re nil t)
  3273.       ;; Ooops.  Must be in a macro with distributed args.
  3274.       (re-search-forward (format reftex-find-label-regexp-format2
  3275.                      (regexp-quote label)) nil t)))
  3276.       (when (match-end 3)
  3277.         (reftex-highlight 0 (match-beginning 3) (match-end 3))
  3278.         (reftex-show-entry (- (point) (match-beginning 3))
  3279.                            (- (point) (match-end 3)))
  3280.         (recenter (/ (window-height) 2)))
  3281.       (select-window this-window))))
  3282.  
  3283. (defun reftex-pop-to-label (label file-list &optional mark-to-kill highlight)
  3284.   ;; Find LABEL in any file in FILE-LIST in another window.
  3285.   ;; If mark-to-kill is non-nil, mark new buffer for killing.
  3286.   ;; If HIGHLIGHT is non-nil, highlight the label definition.
  3287.   (let* ((re1 (format reftex-find-label-regexp-format (regexp-quote label)))
  3288.      (re2 (format reftex-find-label-regexp-format2 (regexp-quote label)))
  3289.      (re-list (list re1 re2)) re
  3290.      (file-list-1 file-list)
  3291.          file buf)
  3292.     (catch 'exit
  3293.       (while (setq re (pop re-list))
  3294.     (setq file-list file-list-1)
  3295.     (while (setq file (pop file-list))
  3296.       (unless (setq buf (reftex-get-file-buffer-force file mark-to-kill))
  3297.         (error "No such file %s" file))
  3298.       (set-buffer buf)
  3299.       (widen)
  3300.       (goto-char (point-min))
  3301.       (when (re-search-forward re nil t)
  3302.         (switch-to-buffer-other-window buf)
  3303.         (goto-char (match-beginning 0))
  3304.         (recenter (/ (window-height) 2))
  3305.         (if highlight
  3306.         (reftex-highlight 0 (match-beginning 3) (match-end 3)))
  3307.         (throw 'exit (selected-window)))))
  3308.       (error "Label %s not found" label))))
  3309.  
  3310. (defun reftex-find-duplicate-labels ()
  3311.   "Produce a list of all duplicate labels in the document."
  3312.  
  3313.   (interactive)
  3314.  
  3315.   ;; Rescan the document to make sure
  3316.   (reftex-access-scan-info t)
  3317.  
  3318.   (let ((master (reftex-TeX-master-file))
  3319.     (cnt 0)
  3320.         (dlist
  3321.          (mapcar
  3322.       (function
  3323.        (lambda (x)
  3324.          (let (x1)
  3325.            (cond
  3326.         ((memq (car x)
  3327.                '(toc bof eof bib thebib label-numbers xr xr-doc
  3328.                  master-dir file-error appendix is-multi))
  3329.          nil)
  3330.         (t
  3331.          (setq x1 (reftex-all-assoc-string
  3332.                (car x) (symbol-value reftex-docstruct-symbol)))
  3333.          (if (< 1 (length x1))
  3334.              (append (list (car x))
  3335.                  (mapcar (function
  3336.                       (lambda(x)
  3337.                     (abbreviate-file-name (nth 3 x))))
  3338.                      x1))
  3339.            (list nil)))))))
  3340.           (reftex-uniquify (symbol-value reftex-docstruct-symbol)))))
  3341.  
  3342.     (setq dlist (reftex-uniquify dlist))
  3343.     (if (null dlist) (error "No duplicate labels in document"))
  3344.     (switch-to-buffer-other-window "*Duplicate Labels*")
  3345.     (make-local-variable 'TeX-master)
  3346.     (setq TeX-master master)
  3347.     (erase-buffer)
  3348.     (insert "                MULTIPLE LABELS IN CURRENT DOCUMENT:\n")
  3349.     (insert 
  3350.      " Move point to label and type `r' to run a query-replace on the label\n"
  3351.      " and its references.  Type `q' to exit this buffer.\n\n")
  3352.     (insert " LABEL               FILE\n")
  3353.     (insert " -------------------------------------------------------------\n")
  3354.     (use-local-map (make-sparse-keymap))
  3355.     (local-set-key [?q] (function
  3356.              (lambda () (interactive)
  3357.                (kill-buffer (current-buffer)) (delete-window))))
  3358.     (local-set-key [?r] 'reftex-change-label)
  3359.     (while dlist
  3360.       (when (and (car (car dlist))
  3361.                  (cdr (car dlist)))
  3362.     (incf cnt)
  3363.         (insert (mapconcat 'identity (car dlist) "\n    ") "\n"))
  3364.       (pop dlist))
  3365.     (goto-char (point-min))
  3366.     (when (= cnt 0)
  3367.       (kill-buffer (current-buffer))
  3368.       (delete-window)
  3369.       (message "Document does not contain duplicate labels."))))
  3370.  
  3371. (defun reftex-all-assq (key list)
  3372.   ;; Return a list of all associations of KEY in LIST.  Comparison with string=
  3373.   (let (rtn)
  3374.     (while (setq list (memq (assq key list) list))
  3375.       (push (car list) rtn)
  3376.       (pop list))
  3377.     (nreverse rtn)))
  3378.  
  3379. (defun reftex-all-assoc-string (key list)
  3380.   ;; Return a list of all associations of KEY in LIST.  Comparison with string=
  3381.   (let (rtn)
  3382.     (while list
  3383.       (if (string= (car (car list)) key)
  3384.           (push (car list) rtn))
  3385.       (pop list))
  3386.     (nreverse rtn)))
  3387.  
  3388. (defun reftex-kill-temporary-buffers (&optional buffer)
  3389.   ;; Kill all buffers in the list reftex-kill-temporary-buffers.
  3390.   (cond
  3391.    (buffer
  3392.     (when (member buffer reftex-buffers-to-kill)
  3393.       (kill-buffer buffer)
  3394.       (setq reftex-buffers-to-kill
  3395.             (delete buffer reftex-buffers-to-kill))))
  3396.    (t
  3397.     (while (setq buffer (pop reftex-buffers-to-kill))
  3398.       (when (bufferp buffer)
  3399.         (and (buffer-modified-p buffer)
  3400.              (y-or-n-p (format "Save file %s? "
  3401.                                (buffer-file-name buffer)))
  3402.              (save-excursion
  3403.                (set-buffer buffer)
  3404.                (save-buffer)))
  3405.         (kill-buffer buffer))
  3406.       (pop reftex-buffers-to-kill)))))
  3407.  
  3408. (defun reftex-show-entry (beg-hlt end-hlt)
  3409.   ;; Show entry if point is hidden by outline mode
  3410.   (let* ((pos (point))
  3411.          (n (/ (window-height) 2))
  3412.          (beg (save-excursion
  3413.                (re-search-backward "[\n\r]" nil 1 n) (point)))
  3414.          (end (save-excursion
  3415.                 (re-search-forward  "[\n\r]" nil 1 n) (point))))
  3416.     (if (and reftex-auto-show-entry
  3417.              (string-match
  3418.               "\r" (buffer-substring beg end)))
  3419.         (cond
  3420.          ((eq t reftex-auto-show-entry)
  3421.           (subst-char-in-region
  3422.            (save-excursion (search-backward "\n" nil t) (point))
  3423.            (save-excursion (search-forward  "\n" nil t) (point))
  3424.            ?\r ?\n t))
  3425.          ((eq reftex-auto-show-entry 'copy)
  3426.           (let ((string (buffer-substring beg end)))
  3427.             (switch-to-buffer "*RefTeX Context Copy*")
  3428.             (setq buffer-read-only nil)
  3429.             (erase-buffer)
  3430.             (insert string)
  3431.             (subst-char-in-region (point-min) (point-max) ?\r ?\n t)
  3432.             (goto-char (- pos beg))
  3433.             (reftex-highlight 0 (1+ (- (point) beg-hlt))
  3434.                               (1+ (- (point) end-hlt)))
  3435.             (when (reftex-refontify)
  3436.               (set (make-local-variable 'font-lock-defaults) nil)
  3437.           (let ((major-mode 'latex-mode))
  3438.         (font-lock-mode 1)))
  3439.             (setq buffer-read-only t)))
  3440.          ))))
  3441.  
  3442. (defun reftex-nicify-text (text)
  3443.   ;; Make TEXT nice for inclusion as context into label menu
  3444.   ;; remove line breaks and extra white space
  3445.   (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
  3446.     (setq text (replace-match " " nil t text)))
  3447.   ;; cut before the next `\end{' or `\item' or `\\'
  3448.   (if (string-match "\\(\\\\end{\\|\\\\item\\|\\\\\\\\\\).*" text)
  3449.       (setq text (replace-match "" nil t text)))
  3450.   ;; kill the embedded label
  3451.   (if (string-match "\\\\label{[^}]*}" text)
  3452.       (setq text (replace-match "" nil t text)))
  3453.   ;; remove leading garbage
  3454.   (if (string-match "\\`[ }]+" text)
  3455.       (setq text (replace-match "" nil t text)))
  3456.   ;; limit length
  3457.   (cond
  3458.    ((> (length text) 100) (substring text 0 100))
  3459.    ((= (length text) 0) " ")
  3460.    (t text)))
  3461.  
  3462. (defun reftex-typekey-check (typekey conf-variable &optional n)
  3463.   ;; Check if CONF-VARIABLE is true or contains TYPEKEY
  3464.   (and n (setq conf-variable (nth n conf-variable)))
  3465.   (or (eq conf-variable t)
  3466.       (and (stringp conf-variable)
  3467.            (string-match (concat "[" conf-variable "]") typekey))))
  3468.  
  3469. ;;; ===========================================================================
  3470. ;;;
  3471. ;;; Table of contents
  3472.  
  3473. ;; We keep at most one *toc* buffer - it is easy to make them
  3474.  
  3475. (defvar reftex-toc-map (make-sparse-keymap)
  3476.   "Keymap used for *toc* buffer.")
  3477.  
  3478. (defvar reftex-last-toc-master nil
  3479.   "Stores the name of the tex file that `reftex-toc' was last run on.")
  3480.  
  3481. (defvar reftex-last-toc-file nil
  3482.   "Stores the file name from which `reftex-toc' was called.  For redo command.")
  3483.  
  3484. (defvar reftex-last-window-height nil)
  3485.  
  3486. (defvar reftex-toc-return-marker (make-marker)
  3487.   "Marker which makes it possible to return from toc to old position.")
  3488.  
  3489. (defconst reftex-toc-help
  3490. "                      AVAILABLE KEYS IN TOC BUFFER
  3491.                       ============================
  3492. n / p   next-line / previous-line
  3493. SPC     Show the corresponding section of the LaTeX document.
  3494. TAB     Goto the section.
  3495. RET     Goto the section and hide the *toc* buffer (also on mouse-2).
  3496. q / Q   Hide/Kill *toc* buffer, return to position of last reftex-toc command.
  3497. f / g   Toggle follow mode on and off / Refresh *toc* buffer.
  3498. r / R   Reparse the LaTeX document / Reparse entire LaTeX document.
  3499. x       Switch to TOC of external document (with LaTeX package `xr').")
  3500.  
  3501. (defun reftex-toc ()
  3502.   "Show the table of contents for the current document.
  3503. When called with a raw C-u prefix, rescan the document first."
  3504.  
  3505.   (interactive)
  3506.  
  3507.   (if (or (not (string= reftex-last-toc-master (reftex-TeX-master-file)))
  3508.           current-prefix-arg)
  3509.       (reftex-empty-toc-buffer))
  3510.  
  3511.   (setq reftex-last-toc-file   (buffer-file-name))
  3512.   (setq reftex-last-toc-master (reftex-TeX-master-file))
  3513.  
  3514.   (set-marker reftex-toc-return-marker (point))
  3515.  
  3516.   ;; If follow mode is active, arrange to delay it one command
  3517.   (if reftex-toc-follow-mode
  3518.       (setq reftex-toc-follow-mode 1))
  3519.  
  3520.   ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
  3521.   (reftex-access-scan-info current-prefix-arg)
  3522.  
  3523.   (let* ((all   (symbol-value reftex-docstruct-symbol))
  3524.      (xr-data (assq 'xr all))
  3525.      (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
  3526.          (where (reftex-nearest-section))
  3527.          toc1 cell startpos)
  3528.  
  3529.     (if (get-buffer-window "*toc*")
  3530.         (select-window (get-buffer-window "*toc*"))
  3531.       (when (< (window-height) (* 2 window-min-height))
  3532.     (delete-other-windows))
  3533.       (setq reftex-last-window-height (window-height))  ; remember
  3534.       (split-window)
  3535.       (switch-to-buffer (get-buffer-create "*toc*")))
  3536.  
  3537.     (cond
  3538.      ;; buffer is empty - fill it with the table of contents
  3539.      ((= (buffer-size) 0)
  3540.       (message "Building *toc* buffer...")
  3541.       (make-local-variable 'revert-buffer-function)
  3542.       (setq revert-buffer-function 'reftex-toc-revert)
  3543.       (setq truncate-lines t)
  3544.       (make-local-hook 'post-command-hook)
  3545.       (make-local-hook 'pre-command-hook)
  3546.       (setq post-command-hook '(reftex-toc-post-command-hook))
  3547.       (setq pre-command-hook  '(reftex-toc-pre-command-hook))
  3548.       (use-local-map reftex-toc-map)
  3549.  
  3550.       (insert (format
  3551. "TABLE-OF-CONTENTS on %s
  3552. SPC=view TAB=goto RET=goto+hide [q]uit [r]escan [f]ollow-mode e[x]tern [?]Help
  3553. -------------------------------------------------------------------------------
  3554. " (abbreviate-file-name reftex-last-toc-master)))
  3555.       (setq startpos (point))
  3556.  
  3557.       (if (reftex-use-fonts)
  3558.           (put-text-property 1 (point) 'face 'font-lock-keyword-face))
  3559.       (put-text-property 1 (point) 'intangible t)
  3560.       (put-text-property 1 2 'xr-alist xr-alist)
  3561.  
  3562.       (while all
  3563.         (setq cell (car all)
  3564.               all  (cdr all))
  3565.         (when (eq (car cell) 'toc)
  3566.           (setq toc1 (concat (nth 2 cell) "\n"))
  3567.           (put-text-property 0 (length toc1) 'toc cell toc1)
  3568.           (insert toc1)))
  3569.  
  3570.       (backward-delete-char 1)
  3571.  
  3572.       (message "Building *toc* buffer...done.")
  3573.       (setq buffer-read-only t))
  3574.      (t
  3575.       (goto-line 3)
  3576.       (beginning-of-line)
  3577.       (setq startpos (point))))
  3578.  
  3579.     ;; Find the correct section
  3580.     (goto-char (point-max))
  3581.     (beginning-of-line)
  3582.     (while (and (> (point) startpos)
  3583.                 (not (eq (get-text-property (point) 'toc) where)))
  3584.       (beginning-of-line 0))))
  3585.  
  3586. (defun reftex-nearest-section ()
  3587.   ;; Return (file . find) of nearest section command
  3588.   (let* ((here-I-am (car (reftex-where-am-I))))
  3589.     (reftex-last-assoc-before-elt
  3590.      'toc here-I-am (symbol-value reftex-docstruct-symbol))))
  3591.  
  3592. (defun reftex-toc-pre-command-hook ()
  3593.   ;; used as pre command hook in *toc* buffer
  3594.   (reftex-unhighlight 0)
  3595.   (reftex-unhighlight 1))
  3596.  
  3597. (defun reftex-toc-post-command-hook ()
  3598.   ;; used in the post-command-hook for the *toc* buffer
  3599.   (and (> (point) 1)
  3600.        (save-excursion
  3601.          (reftex-highlight 1
  3602.                           (progn (beginning-of-line) (point))
  3603.                           (progn (end-of-line) (point)))))
  3604.   (cond
  3605.    ((integerp reftex-toc-follow-mode)
  3606.     ;; remove delayed action
  3607.     (setq reftex-toc-follow-mode t))
  3608.    (reftex-toc-follow-mode
  3609.     ;; show context in other window
  3610.     (condition-case nil
  3611.         (reftex-toc-visit-line nil (not reftex-revisit-to-follow))
  3612.       (error t)))))
  3613.  
  3614. (defun reftex-empty-toc-buffer ()
  3615.   (if (get-buffer "*toc*")
  3616.       (save-excursion
  3617.         (set-buffer "*toc*")
  3618.         (setq buffer-read-only nil)
  3619.         (erase-buffer))))
  3620.  
  3621. (defun reftex-re-enlarge ()
  3622.   (enlarge-window
  3623.    (max 0 (- (or reftex-last-window-height (window-height))
  3624.              (window-height)))))
  3625.  
  3626. (defun reftex-toc-show-help ()
  3627.   (interactive)
  3628.   (with-output-to-temp-buffer "*RefTeX Help*"
  3629.     (princ reftex-toc-help))
  3630.   ;; If follow mode is active, arrange to delay it one command
  3631.   (if reftex-toc-follow-mode
  3632.       (setq reftex-toc-follow-mode 1)))
  3633.  
  3634. (defun reftex-toc-toggle-follow ()
  3635.   "Toggle toc-follow mode.
  3636. (It is not really a mode, just a flag)."
  3637.   (interactive)
  3638.   (setq reftex-toc-follow-mode (not reftex-toc-follow-mode)))
  3639. (defun reftex-toc-view-line ()
  3640.   "View document location in other window."
  3641.   (interactive)
  3642.   (reftex-toc-visit-line))
  3643. (defun reftex-toc-goto-line-and-hide ()
  3644.   "Go to document location in other window.  Hide the *toc* window."
  3645.   (interactive)
  3646.   (reftex-toc-visit-line 'hide))
  3647. (defun reftex-toc-goto-line ()
  3648.   "Go to document location in other window.  Hide the *toc* window."
  3649.   (interactive)
  3650.   (reftex-toc-visit-line t))
  3651. (defun reftex-toc-mouse-goto-line-and-hide (ev)
  3652.   "Go to document location in other window.  Hide the *toc* window."
  3653.   (interactive "e")
  3654.   (mouse-set-point ev)
  3655.   (reftex-toc-visit-line 'hide))
  3656. (defun reftex-toc-quit ()
  3657.   "Hide the *toc* window and do not move point."
  3658.   (interactive)
  3659.   (or (one-window-p) (delete-window))
  3660.   (switch-to-buffer (marker-buffer reftex-toc-return-marker))
  3661.   (reftex-re-enlarge)
  3662.   (goto-char (or (marker-position reftex-toc-return-marker) (point))))
  3663. (defun reftex-toc-quit-and-kill ()
  3664.   "Kill the *toc* buffer."
  3665.   (interactive)
  3666.   (kill-buffer "*toc*")
  3667.   (or (one-window-p) (delete-window))
  3668.   (switch-to-buffer (marker-buffer reftex-toc-return-marker))
  3669.   (reftex-re-enlarge)
  3670.   (goto-char (marker-position reftex-toc-return-marker)))
  3671. (defun reftex-toc-rescan (&rest ignore)
  3672.   "Regenerate the *toc* buffer by reparsing file of section at point."
  3673.   (interactive)
  3674.   (if reftex-enable-partial-scans
  3675.       (let ((file (nth 3 (get-text-property (point) 'toc))))
  3676.         (if (not file)
  3677.             (error "Don't know which file to rescan.  Try `R'.")
  3678.           (switch-to-buffer-other-window
  3679.            (reftex-get-file-buffer-force file))
  3680.           (setq current-prefix-arg '(4))
  3681.           (reftex-toc)))
  3682.     (reftex-toc-Rescan))
  3683.   (reftex-kill-temporary-buffers))
  3684. (defun reftex-toc-Rescan (&rest ignore)
  3685.   "Regenerate the *toc* buffer by reparsing the entire document."
  3686.   (interactive)
  3687.   (switch-to-buffer-other-window
  3688.    (reftex-get-file-buffer-force reftex-last-toc-file))
  3689.   (setq current-prefix-arg '(16))
  3690.   (reftex-toc))
  3691. (defun reftex-toc-revert (&rest ignore)
  3692.   "Regenerate the *toc* from the internal lists."
  3693.   (interactive)
  3694.   (switch-to-buffer-other-window
  3695.    (reftex-get-file-buffer-force reftex-last-toc-file))
  3696.   (reftex-empty-toc-buffer)
  3697.   (setq current-prefix-arg nil)
  3698.   (reftex-toc))
  3699. (defun reftex-toc-external (&rest ignore)
  3700.   "Switch to table of contents of an external document."
  3701.   (interactive)
  3702.   (let* ((old-buf (current-buffer))
  3703.      (xr-alist (get-text-property 1 'xr-alist))
  3704.      (xr-index (reftex-select-external-document
  3705.            xr-alist 0)))
  3706.     (switch-to-buffer-other-window (or (reftex-get-file-buffer-force
  3707.                     (cdr (nth xr-index xr-alist)))
  3708.                        (error "Cannot switch document")))
  3709.     (reftex-toc)
  3710.     (if (equal old-buf (current-buffer))
  3711.     (message "")
  3712.       (message "Switched document"))))
  3713.  
  3714. (defun reftex-toc-visit-line (&optional final no-revisit)
  3715.   ;; Visit the tex file corresponding to the toc entry on the current line.
  3716.   ;; If FINAL is t, stay there
  3717.   ;; If FINAL is 'hide, hide the *toc* window.
  3718.   ;; Otherwise, move cursor back into *toc* window.
  3719.   ;; This function is pretty clever about finding back a section heading,
  3720.   ;; even if the buffer is not live, or things like outline, x-symbol etc.
  3721.   ;; have been active.
  3722.  
  3723.   (let* ((toc (get-text-property (point) 'toc))
  3724.          (file (nth 3 toc))
  3725.          (marker (nth 4 toc))
  3726.          (level (nth 5 toc))
  3727.          (literal (nth 7 toc))
  3728.          (emergency-point (nth 8 toc))
  3729.          (toc-window (selected-window))
  3730.          show-window show-buffer match)
  3731.  
  3732.     (unless toc (error "Don't know which toc line to visit"))
  3733.  
  3734.     (setq match
  3735.           (cond
  3736.            ((and (markerp marker) (marker-buffer marker))
  3737.             ;; Buffer is still live and we have the marker.  Should be easy.
  3738.             (switch-to-buffer-other-window (marker-buffer marker))
  3739.             (goto-char (marker-position marker))
  3740.             (or (looking-at (regexp-quote literal))
  3741.                 (looking-at (reftex-make-regexp-allow-for-ctrl-m literal))
  3742.                 (looking-at (reftex-make-desperate-section-regexp literal))
  3743.                 (looking-at (concat "\\\\"
  3744.                                     (regexp-quote
  3745.                                      (car (rassq level reftex-section-levels)))
  3746.                                     "[[{]"))))
  3747.            ((or (not no-revisit)
  3748.         (get-file-buffer file))
  3749.             ;; Marker is lost.  Use the backup method.
  3750.             (switch-to-buffer-other-window
  3751.              (reftex-get-file-buffer-force file nil))
  3752.             (goto-char (or emergency-point (point-min)))
  3753.             (or (looking-at (regexp-quote literal))
  3754.                 (let ((pos (point)))
  3755.                   (re-search-backward "\\`\\|[\r\n][ \t]*[\r\n]" nil t)
  3756.                   (or (reftex-nearest-match (regexp-quote literal) pos)
  3757.                       (reftex-nearest-match
  3758.                        (reftex-make-regexp-allow-for-ctrl-m literal) pos)
  3759.                       (reftex-nearest-match
  3760.                        (reftex-make-desperate-section-regexp literal) pos)))))
  3761.            ))
  3762.  
  3763.     (setq show-window (selected-window)
  3764.           show-buffer (current-buffer))
  3765.  
  3766.     (unless match
  3767.       (select-window toc-window)
  3768.       (error "Cannot find line"))
  3769.  
  3770.     (goto-char (match-beginning 0))
  3771.     (recenter 1)
  3772.     (reftex-highlight 0 (match-beginning 0) (match-end 0) (current-buffer))
  3773.  
  3774.     (select-window toc-window)
  3775.  
  3776.     ;; use the `final' parameter to decide what to do next
  3777.     (cond
  3778.      ((eq final t)
  3779.       (reftex-unhighlight 0)
  3780.       (select-window show-window))
  3781.      ((eq final 'hide)
  3782.       (reftex-unhighlight 0)
  3783.       (or (one-window-p) (delete-window))
  3784.       (switch-to-buffer show-buffer)
  3785.       (reftex-re-enlarge))
  3786.      (t nil))))
  3787.  
  3788. ;;; ===========================================================================
  3789. ;;;
  3790. ;;; BibTeX citations.
  3791.  
  3792. ;; Variables and constants
  3793.  
  3794. ;; Define variable to silence compiler warnings
  3795. (defvar reftex-cite-format-builtin)
  3796.  
  3797. ;; The history list of regular expressions used for citations
  3798. (defvar reftex-cite-regexp-hist nil)
  3799.  
  3800. ;; Prompt and help string for citation selection
  3801. (defconst reftex-citation-prompt
  3802.   "Select: [n]ext [p]revious [r]estrict [ ]full_entry [q]uit RET [?]Help+more")
  3803.  
  3804. (defconst reftex-citation-help
  3805.   " n / p      Go to next/previous entry (Cursor motion works as well).
  3806.  C-s / C-r  Search forward/backward.  Use repeated C-s/C-r as in isearch.
  3807.  g   / r    Start over with new regexp / Refine with additional regexp.
  3808.  SPC        Show full database entry in other window.
  3809.  f          Toggle follow mode: Other window will follow with full db entry.
  3810.  q          Quit without inserting \\cite macro into buffer.
  3811.  e          Recursive edit into other window.
  3812.  TAB        Enter citation key with completion.
  3813.  RET  / a   Accept current entry / Accept all entries.")
  3814.  
  3815. (defvar reftex-select-bib-map nil
  3816.   "Keymap used for *RefTeX Select* buffer, when selecting a BibTeX entry.
  3817. This keymap can be used to configure the BibTeX selection process which is
  3818. started with the command \\[reftex-citation].")
  3819.  
  3820. ;; Find bibtex files
  3821.  
  3822. (defun reftex-get-bibfile-list ()
  3823.   ;; Return list of bibfiles for current document.
  3824.   ;; When using the chapterbib or bibunits package you should either
  3825.   ;; use the same database files everywhere, or separate parts using
  3826.   ;; different databases into different files (included into the mater file).
  3827.   ;; Then this function will return the applicable database files.
  3828.  
  3829.   ;; Ensure access to scanning info
  3830.   (reftex-access-scan-info)
  3831.   (or
  3832.    ;; Try inside this file (and its includes)
  3833.    (cdr (reftex-last-assoc-before-elt
  3834.          'bib (list 'eof (buffer-file-name))
  3835.          (member (list 'bof (buffer-file-name))
  3836.                  (symbol-value reftex-docstruct-symbol))))
  3837.    ;; Try after the beginning of this file
  3838.    (cdr (assq 'bib (member (list 'bof (buffer-file-name))
  3839.                            (symbol-value reftex-docstruct-symbol))))
  3840.    ;; Anywhere in the entire document
  3841.    (cdr (assq 'bib (symbol-value reftex-docstruct-symbol)))
  3842.    (error "\\bibliography statement missing or .bib files not found.")))
  3843.  
  3844. (defun reftex-find-tex-file (file master-dir &optional die)
  3845.   ;; Find FILE in MASTER-DIR or on reftex-tex-path.
  3846.   ;; FILE may be given without the .tex extension.
  3847.   (cond 
  3848.    ((file-name-absolute-p file)
  3849.     (if (file-exists-p file) file nil))
  3850.    (t
  3851.     (reftex-access-search-path "tex")
  3852.     (let* ((path (cons master-dir reftex-tex-path))
  3853.        file1)
  3854.       (setq file1
  3855.         (or (reftex-find-file-on-path (concat file ".tex") path)
  3856.         (reftex-find-file-on-path file path)))
  3857.       (unless file1
  3858.     (reftex-access-search-path "tex" t file)
  3859.     (setq path (cons master-dir reftex-tex-path))
  3860.     (setq file1
  3861.           (or (reftex-find-file-on-path (concat file ".tex") path)
  3862.           (reftex-find-file-on-path file path))))
  3863.       (cond (file1 file1)
  3864.         (die (error "No such file: %s" file) nil)
  3865.         (t (message "No such file: %s (ignored)" file) nil))))))
  3866.  
  3867. (defun reftex-find-bib-file (file master-dir &optional die)
  3868.   ;; Find FILE in MASTER-DIR or on reftex-bib-path
  3869.   (reftex-access-search-path "bib")
  3870.   (let ((file1 (reftex-find-file-on-path 
  3871.         file (cons master-dir reftex-bib-path))))
  3872.     (unless file1
  3873.       (reftex-access-search-path "bib" t file)
  3874.       (setq file1 (reftex-find-file-on-path 
  3875.         file (cons master-dir reftex-bib-path))))
  3876.     (cond (file1 file1)
  3877.       (die (error "No such file: %s" file) nil)
  3878.       (t (message "No such file: %s (ignored)" file) nil))))
  3879.  
  3880. ;; Find a certain reference in any of the BibTeX files.
  3881.  
  3882. (defun reftex-pop-to-bibtex-entry (key file-list
  3883.                                       &optional mark-to-kill highlight item)
  3884.   ;; Find BibTeX KEY in any file in FILE-LIST in another window.
  3885.   ;; If MARK-TO-KILL is non-nil, mark new buffer to kill.
  3886.   ;; If HIGHLIGHT is non-nil, highlight the match.
  3887.   ;; If ITEM in non-nil, search for bibitem instead of database entry.
  3888.  
  3889.   (let* ((re
  3890.       (if item 
  3891.           (concat "\\\\bibitem\\(\\[[^]]*\\]\\)?{" (regexp-quote key) "}")
  3892.         (concat "@[a-zA-Z]+[ \t\n\r]*[{(][ \t\n\r]*" (regexp-quote key))))
  3893.          (window-conf (current-window-configuration))
  3894.          file buf)
  3895.  
  3896.     (catch 'exit
  3897.       (switch-to-buffer-other-window (current-buffer))
  3898.       (while file-list
  3899.         (setq file (car file-list)
  3900.               file-list (cdr file-list))
  3901.         (unless (setq buf (reftex-get-file-buffer-force file mark-to-kill))
  3902.           (error "No such file %s" file))
  3903.         (switch-to-buffer buf)
  3904.         (widen)
  3905.         (goto-char (point-min))
  3906.         (when (re-search-forward re nil t)
  3907.           (goto-char (match-beginning 0))
  3908.           (recenter 0)
  3909.           (if highlight
  3910.               (reftex-highlight 0 (match-beginning 0) (match-end 0)))
  3911.           (throw 'exit (selected-window))))
  3912.       (set-window-configuration window-conf)
  3913.       (if item
  3914.       (message "No \\bibitem with citation key %s" key)
  3915.     (message "No BibTeX entry with citation key %s" key)))))
  3916.  
  3917. ;; Parse bibtex buffers
  3918.  
  3919. (defun reftex-extract-bib-entries (buffers &optional get-word)
  3920.   ;; Extract bib entries which match regexps from BUFFERS.
  3921.   ;; BUFFERS is a list of buffers or file names.
  3922.   ;; Return list with entries."
  3923.   (let* (re-list first-re rest-re
  3924.                  (buffer-list (if (listp buffers) buffers (list buffers)))
  3925.                  found-list entry buffer1 buffer alist
  3926.                  key-point start-point end-point)
  3927.  
  3928.     (setq re-list (split-string 
  3929.            (read-string "RegExp [ && RegExp...]: "
  3930.                 nil 'reftex-cite-regexp-hist)
  3931.            "[ \t]*&&[ \t]*"))
  3932.  
  3933.     (setq first-re (car re-list)    ; We'll use the first re to find things,
  3934.           rest-re  (cdr re-list))   ; the others to narrow down.
  3935.     (if (string-match "\\`[ \t]*\\'" first-re)
  3936.         (error "Empty regular expression"))
  3937.  
  3938.     (save-excursion
  3939.       (save-window-excursion
  3940.  
  3941.         ;; Walk through all bibtex files
  3942.         (while buffer-list
  3943.           (setq buffer (car buffer-list)
  3944.                 buffer-list (cdr buffer-list))
  3945.           (if (and (bufferp buffer)
  3946.                    (buffer-live-p buffer))
  3947.               (setq buffer1 buffer)
  3948.             (setq buffer1 (reftex-get-file-buffer-force
  3949.                            buffer (not reftex-keep-temporary-buffers))))
  3950.           (if (not buffer1)
  3951.               (error "Cannot find BibTeX file %s" buffer)
  3952.             (message "Scanning bibliography database %s" buffer1))
  3953.  
  3954.           (set-buffer buffer1)
  3955.           (save-excursion
  3956.             (goto-char (point-min))
  3957.             (while (re-search-forward first-re nil t)
  3958.               (catch 'search-again
  3959.                 (setq key-point (point))
  3960.                 (unless (re-search-backward
  3961.                          "\\(\\`\\|[\n\r]\\)[ \t]*@\\([a-zA-Z]+\\)[ \t\n\r]*[{(]" nil t)
  3962.                   (throw 'search-again nil))
  3963.                 (setq start-point (point))
  3964.                 (goto-char (match-end 0))
  3965.                 (condition-case nil
  3966.                     (up-list 1)
  3967.                   (error (goto-char key-point)
  3968.                           (throw 'search-again nil)))
  3969.                 (setq end-point (point))
  3970.  
  3971.                 ;; Ignore @string, @comment and @c entries or things
  3972.                 ;; outside entries
  3973.                 (when (or (string= (downcase (match-string 2)) "string")
  3974.                           (string= (downcase (match-string 2)) "comment")
  3975.                           (string= (downcase (match-string 2)) "c")
  3976.                           (< (point) key-point)) ; this means match not in {}
  3977.                   (goto-char key-point)
  3978.                   (throw 'search-again nil))
  3979.  
  3980.                 ;; Well, we have got a match
  3981.                 (setq entry (concat
  3982.                              (buffer-substring start-point (point)) "\n"))
  3983.  
  3984.                 ;; Check if other regexp match as well
  3985.                 (setq re-list rest-re)
  3986.                 (while re-list
  3987.                   (unless (string-match (car re-list) entry)
  3988.                     ;; nope - move on
  3989.                     (throw 'search-again nil))
  3990.                   (pop re-list))
  3991.  
  3992.                 (setq alist (reftex-parse-bibtex-entry
  3993.                              nil start-point end-point))
  3994.                 (push (cons "&entry" entry) alist)
  3995.  
  3996.                 ;; check for crossref entries
  3997.                 (if (assoc "crossref" alist)
  3998.                     (setq alist
  3999.                           (append
  4000.                            alist (reftex-get-crossref-alist alist))))
  4001.  
  4002.                 ;; format the entry
  4003.                 (push (cons "&formatted" (reftex-format-bib-entry alist))
  4004.                       alist)
  4005.  
  4006.                 ;; add it to the list
  4007.                 (push alist found-list))))
  4008.           (reftex-kill-temporary-buffers))))
  4009.     (setq found-list (nreverse found-list))
  4010.  
  4011.     ;; Sorting
  4012.     (cond
  4013.      ((eq 'author reftex-sort-bibtex-matches)
  4014.       (sort found-list 'reftex-bib-sort-author))
  4015.      ((eq 'year   reftex-sort-bibtex-matches)
  4016.       (sort found-list 'reftex-bib-sort-year))
  4017.      ((eq 'reverse-year reftex-sort-bibtex-matches)
  4018.       (sort found-list 'reftex-bib-sort-year-reverse))
  4019.      (t found-list))))
  4020.  
  4021. (defun reftex-bib-sort-author (e1 e2)
  4022.   (let ((al1 (reftex-get-bib-names "author" e1))
  4023.         (al2 (reftex-get-bib-names "author" e2)))
  4024.     (while (and al1 al2 (string= (car al1) (car al2)))
  4025.       (pop al1)
  4026.       (pop al2))
  4027.     (if (and (stringp (car al1))
  4028.              (stringp (car al2)))
  4029.         (string< (car al1) (car al2))
  4030.       (not (stringp (car al1))))))
  4031.  
  4032. (defun reftex-bib-sort-year (e1 e2)
  4033.   (< (string-to-int (cdr (assoc "year" e1)))
  4034.      (string-to-int (cdr (assoc "year" e2)))))
  4035.  
  4036. (defun reftex-bib-sort-year-reverse (e1 e2)
  4037.   (> (string-to-int (or (cdr (assoc "year" e1)) "0"))
  4038.      (string-to-int (or (cdr (assoc "year" e2)) "0"))))
  4039.  
  4040. (defun reftex-get-crossref-alist (entry)
  4041.   ;; return the alist from a crossref entry
  4042.   (let ((crkey (cdr (assoc "crossref" entry)))
  4043.         start)
  4044.     (save-excursion
  4045.       (save-restriction
  4046.         (widen)
  4047.         (if (re-search-forward
  4048.              (concat "@\\w+[{(][ \t\n\r]*" (regexp-quote crkey)
  4049.                      "[ \t\n\r]*,") nil t)
  4050.             (progn
  4051.               (setq start (match-beginning 0))
  4052.               (condition-case nil
  4053.                   (up-list 1)
  4054.                 (error nil))
  4055.               (reftex-parse-bibtex-entry nil start (point)))
  4056.           nil)))))
  4057.  
  4058. ;; Parse the thebibliography environment
  4059. (defun reftex-extract-bib-entries-from-thebibliography (file)
  4060.   ;; Extract bib-entries from the \begin{thebibliography} environment.
  4061.   ;; Parsing is not as good as for the BibTeX database stuff.
  4062.   ;; The environment should be located in file FILE.
  4063.  
  4064.   (let* (start end buf entries re re-list)
  4065.     (unless file
  4066.       (error "Need file name to find thebibliography environment"))
  4067.     (setq buf (reftex-get-file-buffer-force 
  4068.            file (not reftex-keep-temporary-buffers)))
  4069.     (unless buf
  4070.       (error "No such file %s" file))
  4071.     (message "Scanning thebibliography environment in %s" file)
  4072.  
  4073.     (save-excursion
  4074.       (set-buffer buf)
  4075.       (save-restriction
  4076.     (widen)
  4077.     (goto-char (point-min))
  4078.     (if (re-search-forward 
  4079.          "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
  4080.         (progn
  4081.           (beginning-of-line 2)
  4082.           (setq start (point))))
  4083.     (if (re-search-forward 
  4084.          "\\(\\`\\|[\n\r]\\)[ \t]*\\\\end{thebibliography}" nil t)
  4085.         (progn
  4086.           (beginning-of-line 1)
  4087.           (setq end (point))))
  4088.     (when (and start (point))
  4089.       (setq entries 
  4090.         (mapcar 'reftex-parse-bibitem
  4091.            (delete ""
  4092.               (split-string 
  4093.                (buffer-substring-no-properties start end)
  4094.                "[ \t\n\r]*\\\\bibitem\\(\\[[^]]*]\\)*")))))))
  4095.     (unless entries
  4096.       (error "No bibitems found"))
  4097.  
  4098.     (setq re-list (split-string 
  4099.            (read-string "RegExp [ && RegExp...]: "
  4100.                 nil 'reftex-cite-regexp-hist)
  4101.            "[ \t]*&&[ \t]*"))
  4102.     (if (string-match "\\`[ \t]*\\'" (car re-list))
  4103.         (error "Empty regular expression"))
  4104.  
  4105.     (while (and (setq re (pop re-list)) entries)
  4106.       (setq entries 
  4107.         (delete nil (mapcar
  4108.              (function
  4109.               (lambda (x)
  4110.                 (if (string-match re (cdr (assoc "&entry" x)))
  4111.                 x nil)))
  4112.              entries))))
  4113.  
  4114.     (setq entries 
  4115.       (mapcar 
  4116.        (function
  4117.         (lambda (x)
  4118.           (cons (cons "&formatted" (reftex-format-bibitem x)) x)))
  4119.        entries))
  4120.  
  4121.     entries))
  4122.  
  4123. ;; Parse and format individual entries
  4124.  
  4125. (defun reftex-get-bib-names (field entry)
  4126.   ;; Return a list with the author or editor names in ENTRY
  4127.   (let ((names (reftex-get-bib-field field entry)))
  4128.     (if (equal "" names)
  4129.         (setq names (reftex-get-bib-field "editor" entry)))
  4130.     (while (string-match "\\band\\b[ \t]*" names)
  4131.       (setq names (replace-match "\n" nil t names)))
  4132.     (while (string-match "[\\.a-zA-Z\\-]+\\.[ \t]*\\|,.*\\|[{}]+" names)
  4133.       (setq names (replace-match "" nil t names)))
  4134.     (while (string-match "^[ \t]+\\|[ \t]+$" names)
  4135.       (setq names (replace-match "" nil t names)))
  4136.     (while (string-match "[ \t][ \t]+" names)
  4137.       (setq names (replace-match " " nil t names)))
  4138.     (split-string names "\n")))
  4139.  
  4140. (defun reftex-parse-bibtex-entry (entry &optional from to)
  4141.   (let (alist key start field)
  4142.     (save-excursion
  4143.       (save-restriction
  4144.         (if entry
  4145.             (progn
  4146.               (switch-to-buffer "*RefTeX-scratch*")
  4147.               (fundamental-mode)
  4148.               (erase-buffer)
  4149.               (insert entry))
  4150.           (widen)
  4151.           (narrow-to-region from to))
  4152.         (goto-char (point-min))
  4153.  
  4154.         (if (re-search-forward
  4155.              "@\\(\\w+\\)[ \t\n\r]*[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
  4156.             (setq alist
  4157.                   (list
  4158.                    (cons "&type" (downcase (reftex-match-string 1)))
  4159.                    (cons "&key"  (reftex-match-string 2)))))
  4160.         (while (re-search-forward "\\(\\w+\\)[ \t\n\r]*=[ \t\n\r]*" nil t)
  4161.           (setq key (downcase (reftex-match-string 1)))
  4162.           (cond
  4163.            ((= (following-char) ?{)
  4164.             (forward-char 1)
  4165.             (setq start (point))
  4166.             (condition-case nil
  4167.                 (up-list 1)
  4168.               (error nil)))
  4169.            ((= (following-char) ?\")
  4170.             (forward-char 1)
  4171.             (setq start (point))
  4172.             (while (and (search-forward "\"" nil t)
  4173.                         (= ?\\ (char-after (- (point) 2))))))
  4174.            (t
  4175.             (setq start (point))
  4176.             (re-search-forward "[ \t\n\r,}]" nil 1)))
  4177.           (setq field (buffer-substring-no-properties start (1- (point))))
  4178.           ;; remove extra whitespace
  4179.           (while (string-match "[\n\t\r]\\|[ \t][ \t]+" field)
  4180.             (setq field (replace-match " " nil t field)))
  4181.           ;; remove leading garbage
  4182.           (if (string-match "^[ \t{]+" field)
  4183.               (setq field (replace-match "" nil t field)))
  4184.           ;; remove trailing garbage
  4185.           (if (string-match "[ \t}]+$" field)
  4186.               (setq field (replace-match "" nil t field)))
  4187.           (push (cons key field) alist))))
  4188.     alist))
  4189.  
  4190. (defun reftex-get-bib-field (fieldname entry)
  4191.   ;; Extract the field FIELDNAME from an ENTRY
  4192.   (or (cdr (assoc fieldname entry))
  4193.       ""))
  4194.  
  4195. (defun reftex-format-bib-entry (entry)
  4196.   ;; Format a BibTeX ENTRY so that it is nice to look at
  4197.   (let*
  4198.       ((auth-list (reftex-get-bib-names "author" entry))
  4199.        (authors (mapconcat 'identity auth-list ", "))
  4200.        (year      (reftex-get-bib-field "year" entry))
  4201.        (title     (reftex-get-bib-field "title" entry))
  4202.        (type      (reftex-get-bib-field "&type" entry))
  4203.        (key       (reftex-get-bib-field "&key"  entry))
  4204.        (extra
  4205.         (cond
  4206.          ((equal type "article")
  4207.           (concat (reftex-get-bib-field "journal" entry) " "
  4208.                   (reftex-get-bib-field "volume" entry) ", "
  4209.                   (reftex-get-bib-field "pages" entry)))
  4210.          ((equal type "book")
  4211.           (concat "book (" (reftex-get-bib-field "publisher" entry) ")"))
  4212.          ((equal type "phdthesis")
  4213.           (concat "PhD: " (reftex-get-bib-field "school" entry)))
  4214.          ((equal type "mastersthesis")
  4215.           (concat "Master: " (reftex-get-bib-field "school" entry)))
  4216.          ((equal type "inbook")
  4217.           (concat "Chap: " (reftex-get-bib-field "chapter" entry)
  4218.                   ", pp. " (reftex-get-bib-field "pages"   entry)))
  4219.          ((or (equal type "conference")
  4220.               (equal type "incollection")
  4221.               (equal type "inproceedings"))
  4222.           (concat "in: " (reftex-get-bib-field "booktitle" entry)))
  4223.          (t ""))))
  4224.     (setq authors (reftex-truncate authors 30 t t))
  4225.     (when (reftex-use-fonts)
  4226.       (put-text-property 0 (length authors) 'face 'font-lock-keyword-face
  4227.                          authors)
  4228.       (put-text-property 0 (length title)   'face 'font-lock-comment-face
  4229.                          title)
  4230.       (put-text-property 0 (length extra)   'face 'font-lock-reference-face
  4231.                          extra))
  4232.     (concat key "\n     " authors " " year " " extra "\n     " title "\n\n")))
  4233.  
  4234. (defun reftex-parse-bibitem (item)
  4235.   ;; Parse a \bibitem entry
  4236.   (let ((key "") (text ""))
  4237.     (when (string-match "\\`{\\([^}]+\\)}\\([\001-\255]*\\)" item)
  4238.       (setq key (match-string 1 item)
  4239.         text (match-string 2 item)))
  4240.     ;; Clean up the text a little bit
  4241.     (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
  4242.       (setq text (replace-match " " nil t text)))
  4243.     (if (string-match "\\`[ \t]+" text)
  4244.     (setq text (replace-match "" nil t text)))
  4245.     (list
  4246.      (cons "&key" key)
  4247.      (cons "&text" text)
  4248.      (cons "&entry" (concat key " " text)))))
  4249.  
  4250. (defun reftex-format-bibitem (item)
  4251.   ;; Format a \bibitem entry so that it is (relatively) nice to look at.
  4252.   (let ((text (reftex-get-bib-field "&text" item))
  4253.     (key  (reftex-get-bib-field "&key" item))
  4254.     (lines nil))
  4255.  
  4256.     ;; Wrap the text into several lines.
  4257.     (while (and (> (length text) 70)
  4258.         (string-match " " (substring text 60)))
  4259.     (push (substring text 0 (+ 60 (match-beginning 0))) lines)
  4260.     (setq text (substring text (+ 61 (match-beginning 0)))))
  4261.     (push text lines)
  4262.     (setq text (mapconcat 'identity (nreverse lines) "\n     "))
  4263.  
  4264.     (when (reftex-use-fonts)
  4265.       (put-text-property 0 (length text) 'face 'font-lock-comment-face text))
  4266.     (concat key "\n     " text "\n\n")))
  4267.  
  4268. ;; Make a citation
  4269.  
  4270. (defun reftex-citation (&optional no-insert)
  4271.   "Make a citation using BibTeX database files.
  4272. After asking for a Regular Expression, it scans the buffers with
  4273. bibtex entries (taken from the \\bibliography command) and offers the
  4274. matching entries for selection.  The selected entry is formated according
  4275. to `reftex-cite-format' and inserted into the buffer.
  4276. If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
  4277. The regular expression uses an expanded syntax: && is interpreted as `and'.
  4278. Thus, `aaaa&&bbb' matches entries which contain both `aaaa' and `bbb'.
  4279. When this function is called with point inside the braces of a \\cite
  4280. command, it will add another key, ignoring the value of `reftex-cite-format'.
  4281. When called with a numeric prefix, that many citations will be made and all
  4282. put into the same \\cite command.
  4283. When called with just C-u as prefix, enforces rescan of buffer for
  4284. bibliography statement (e.g. if it was changed)."
  4285.  
  4286.   (interactive)
  4287.  
  4288.   ;; check for recursive edit
  4289.   (reftex-check-recursive-edit)
  4290.  
  4291.   ;; if there is just 1 C-u prefix arg, force to rescan buffer
  4292.   (reftex-access-scan-info current-prefix-arg)
  4293.  
  4294.   ;; Call reftex-do-citation, but protected
  4295.   (unwind-protect
  4296.       (reftex-do-citation current-prefix-arg no-insert)
  4297.     (reftex-kill-temporary-buffers)))
  4298.  
  4299. (defun reftex-do-citation (&optional arg no-insert)
  4300.   ;; This really does the work of reftex-citation.
  4301.  
  4302.   ;; Check if there is already a cite command at point and change cite format
  4303.   ;; in order to only add another reference in the same cite command.
  4304.   (let (key format (macro (car (car (reftex-what-macro t)))))
  4305.     (if (and (stringp macro)
  4306.              (string-match "\\`\\\\cite\\|cite\\'" macro))
  4307.         (progn
  4308.           (cond
  4309.            ((or (not arg)
  4310.                 (not (listp arg)))
  4311.             (setq format
  4312.                   (concat
  4313.                    (if (not (or (= (preceding-char) ?{)
  4314.                                 (= (preceding-char) ?,)))
  4315.                        ","
  4316.                      "")
  4317.                    "%l"
  4318.                    (if (not (or (= (following-char) ?})
  4319.                                 (= (following-char) ?,)))
  4320.                        ","
  4321.                      ""))))
  4322.            (t
  4323.             (setq format "%l"))))
  4324.       ;; else: figure out the correct format
  4325.       (setq format
  4326.             (cond
  4327.              ((stringp reftex-cite-format) reftex-cite-format)
  4328.              ((and (symbolp reftex-cite-format)
  4329.                    (assq reftex-cite-format reftex-cite-format-builtin))
  4330.               (nth 2 (assq reftex-cite-format reftex-cite-format-builtin)))
  4331.              (t reftex-cite-format)))
  4332.       (if (listp format)
  4333.           (save-window-excursion
  4334.             (with-output-to-temp-buffer "*RefTeX Select*"
  4335.               (princ "SELECT A CITATION FORMAT\n\n")
  4336.               (princ
  4337.                (mapconcat
  4338.                 (function (lambda (x)
  4339.                             (format "[%c] %s  %s" (car x)
  4340.                                     (if (> (car x) 31) " " "")
  4341.                                     (cdr x))))
  4342.                 format "\n")))
  4343.         (reftex-enlarge-to-fit "*RefTeX Select*")
  4344.             (setq key (read-char))
  4345.             (if (assq key format)
  4346.                 (setq format (cdr (assq key format)))
  4347.               (error "No citation format associated with key `%c'" key)))))
  4348.  
  4349.     (let* (entry data rtn ins-string re-list re found-list found-list-r)
  4350.  
  4351.       ;; Scan bibtex files
  4352.       (setq found-list
  4353.         (cond
  4354.          ((assq 'bib (symbol-value reftex-docstruct-symbol))
  4355.           ;; using BibTeX database files.
  4356.           (reftex-extract-bib-entries (reftex-get-bibfile-list)))
  4357.          ((assq 'thebib (symbol-value reftex-docstruct-symbol))
  4358.           ;; using thebibliography environment.
  4359.           (reftex-extract-bib-entries-from-thebibliography
  4360.            (cdr (assq 'thebib (symbol-value reftex-docstruct-symbol)))))
  4361.          (reftex-default-bibliography
  4362.           (message "Using default bibliography")
  4363.           (reftex-extract-bib-entries reftex-default-bibliography))
  4364.          (t (error "Document does not have a bibliography"))))
  4365.  
  4366.       (unless found-list
  4367.         (error "Sorry, no matches found"))
  4368.  
  4369.       ;; remember where we came from
  4370.       (setq reftex-call-back-to-this-buffer (current-buffer))
  4371.  
  4372.       ;; offer selection
  4373.       (save-window-excursion
  4374.     (delete-other-windows)
  4375.         (switch-to-buffer-other-window "*RefTeX Select*")
  4376.         (erase-buffer)
  4377.         (reftex-insert-bib-matches found-list)
  4378.         (if (= 0 (buffer-size))
  4379.             (error "Sorry, no matches found"))
  4380.         (setq truncate-lines t)
  4381.         (goto-char 1)
  4382.         (if (catch 'exit
  4383.               (while t
  4384.                 (setq rtn
  4385.                       (reftex-select-item
  4386.                        reftex-citation-prompt
  4387.                        reftex-citation-help
  4388.                reftex-select-bib-map
  4389.                        nil
  4390.                        'reftex-bibtex-selection-callback nil))
  4391.                 (setq key (car rtn)
  4392.                       data (nth 1 rtn))
  4393.                 (unless key (throw 'exit nil))
  4394.                 (cond
  4395.                  ((eq key ?g)
  4396.                   (setq found-list
  4397.                         (save-excursion
  4398.                           (set-buffer reftex-call-back-to-this-buffer)
  4399.                           (reftex-extract-bib-entries
  4400.                            (reftex-get-bibfile-list))))
  4401.                   (erase-buffer)
  4402.                   (reftex-insert-bib-matches found-list)
  4403.                   (if (= 0 (buffer-size))
  4404.                       (error "Sorry, no matches found"))
  4405.                   (goto-char 1))
  4406.  
  4407.                  ((eq key ?r)
  4408.                   ;; restrict with new regular expression
  4409.                   (setq re-list
  4410.                         (split-string (read-string
  4411.                        "RegExp [ && RegExp...]: "
  4412.                        nil 'reftex-cite-regexp-hist)
  4413.                        "[ \t]*&&[ \t]*"))
  4414.                   (while re-list
  4415.                     (setq re (car re-list)
  4416.                           re-list (cdr re-list))
  4417.                     (setq found-list-r
  4418.                           (delete ""
  4419.                                   (mapcar
  4420.                    (function
  4421.                     (lambda (x)
  4422.                       (if (string-match
  4423.                        re (cdr (assoc "&entry" x)))
  4424.                       x
  4425.                     "")))
  4426.                                    found-list))))
  4427.                   (if found-list-r
  4428.                       (setq found-list found-list-r)
  4429.                     (ding))
  4430.                   (erase-buffer)
  4431.                   (reftex-insert-bib-matches found-list)
  4432.                   (goto-char 1))
  4433.                  ((eq key ?a)
  4434.                   (setq entry 'all)
  4435.                   (throw 'exit t))
  4436.                  ((or (eq key ?\C-m)
  4437.                       (eq key 'return))
  4438.                   (if data
  4439.                       (setq entry data)
  4440.                     (setq entry nil))
  4441.                   (throw 'exit t))
  4442.          ((stringp key)
  4443.           (setq entry (list (cons "&key" key)))
  4444.                   (throw 'exit t))
  4445.                  (t
  4446.                   (ding)))))
  4447.             (progn
  4448.               ;; format the entry
  4449.               (if (eq entry 'all)
  4450.                   (setq ins-string
  4451.                         (mapconcat
  4452.              (function
  4453.               (lambda (entry)
  4454.                 (if reftex-format-cite-function
  4455.                 (funcall reftex-format-cite-function
  4456.                      (reftex-get-bib-field "&key" entry)
  4457.                      format)
  4458.                   (reftex-format-citation entry format))))
  4459.                          found-list "\n"))
  4460.                 (setq ins-string 
  4461.               (if reftex-format-cite-function
  4462.               (funcall reftex-format-cite-function
  4463.                    (reftex-get-bib-field "&key" entry)
  4464.                    format)
  4465.             (reftex-format-citation entry format)))))
  4466.           (setq ins-string "")
  4467.           (message "Quit")))
  4468.       (kill-buffer "*RefTeX Select*")
  4469.  
  4470.       (unless no-insert
  4471.         (insert ins-string)
  4472.         (when (string-match "\\?" ins-string)
  4473.           (search-backward "?")
  4474.           (delete-char 1)))
  4475.       (message "")
  4476.  
  4477.       ;; Check if the prefix arg was numeric, and call recursively
  4478.       (when (and (integerp arg)
  4479.                  (> arg 1)
  4480.                  (re-search-backward
  4481.                   "\\\\\\([a-zA-Z]*cite\\|cite[a-zA-Z]*\\)\\**\\(\\[[^]]*\\]\\)*{\\([^}]*\\)" nil t))
  4482.         (goto-char (match-end 0))
  4483.         (decf arg)
  4484.         (reftex-do-citation arg))
  4485.  
  4486.       ;; Return the citation key
  4487.       (or (eq entry 'all)
  4488.           (reftex-get-bib-field "&key" entry)))))
  4489.  
  4490. (defun reftex-insert-bib-matches (list)
  4491.   ;; Insert the bib matches and number them correctly
  4492.   (let (tmp)
  4493.     (mapcar 
  4494.      (function
  4495.       (lambda (x)
  4496.     (setq tmp (cdr (assoc "&formatted" x)))
  4497.     (put-text-property 0 (length tmp) ':data x tmp)
  4498.     (insert tmp)))
  4499.      list)))
  4500.  
  4501. (defun reftex-format-names (namelist n)
  4502.   (let (last (len (length namelist)))
  4503.     (cond
  4504.      ((= 1 len) (car namelist))
  4505.      ((> len n) (concat (car namelist) (nth 2 reftex-cite-punctuation)))
  4506.      (t
  4507.       (setq n (min len n)
  4508.             last (nth (1- n) namelist))
  4509.       (setcdr (nthcdr (- n 2) namelist) nil)
  4510.       (concat
  4511.        (mapconcat 'identity namelist (nth 0 reftex-cite-punctuation))
  4512.        (nth 1 reftex-cite-punctuation)
  4513.        last)))))
  4514.  
  4515. (defun reftex-format-citation (entry format)
  4516.   ;; Format a citation from the info in the BibTeX ENTRY
  4517.  
  4518.   (unless (stringp format) (setq format "\\cite{%l}"))
  4519.  
  4520.   (if (and reftex-comment-citations
  4521.            (string-match "%l" reftex-cite-comment-format))
  4522.       (error "reftex-cite-comment-format contains illegal %%l"))
  4523.  
  4524.   (while (string-match
  4525.           "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
  4526.           format)
  4527.     (let ((n (string-to-int (match-string 4 format)))
  4528.           (l (string-to-char (match-string 5 format)))
  4529.           rpl b e)
  4530.       (save-match-data
  4531.         (setq rpl
  4532.               (cond
  4533.                ((= l ?l) (concat
  4534.                           (reftex-get-bib-field "&key" entry)
  4535.                           (if reftex-comment-citations
  4536.                               reftex-cite-comment-format
  4537.                             "")))
  4538.                ((= l ?a) (reftex-format-names
  4539.                           (reftex-get-bib-names "author" entry)
  4540.                           (or n 2)))
  4541.                ((= l ?A) (car (reftex-get-bib-names "author" entry)))
  4542.                ((= l ?b) (reftex-get-bib-field "booktitle" entry))
  4543.                ((= l ?c) (reftex-get-bib-field "chapter" entry))
  4544.                ((= l ?d) (reftex-get-bib-field "edition" entry))
  4545.                ((= l ?e) (reftex-format-names
  4546.                           (reftex-get-bib-names "editor" entry)
  4547.                           (or n 2)))
  4548.                ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
  4549.                ((= l ?h) (reftex-get-bib-field "howpublished" entry))
  4550.                ((= l ?i) (reftex-get-bib-field "institution" entry))
  4551.                ((= l ?j) (reftex-get-bib-field "journal" entry))
  4552.                ((= l ?k) (reftex-get-bib-field "key" entry))
  4553.                ((= l ?m) (reftex-get-bib-field "month" entry))
  4554.                ((= l ?n) (reftex-get-bib-field "number" entry))
  4555.                ((= l ?o) (reftex-get-bib-field "organization" entry))
  4556.                ((= l ?p) (reftex-get-bib-field "pages" entry))
  4557.                ((= l ?P) (car (split-string
  4558.                                (reftex-get-bib-field "pages" entry)
  4559.                                "[- .]+")))
  4560.                ((= l ?s) (reftex-get-bib-field "school" entry))
  4561.                ((= l ?u) (reftex-get-bib-field "publisher" entry))
  4562.                ((= l ?r) (reftex-get-bib-field "address" entry))
  4563.                ((= l ?t) (reftex-get-bib-field "title" entry))
  4564.                ((= l ?v) (reftex-get-bib-field "volume" entry))
  4565.                ((= l ?y) (reftex-get-bib-field "year" entry)))))
  4566.  
  4567.       (if (string= rpl "")
  4568.           (setq b (match-beginning 2) e (match-end 2))
  4569.         (setq b (match-beginning 3) e (match-end 3)))
  4570.       (setq format (concat (substring format 0 b) rpl (substring format e)))))
  4571.   (while (string-match "%%" format)
  4572.     (setq format (replace-match "%" t t format)))
  4573.   (while (string-match "[ ,.;:]*%<" format)
  4574.     (setq format (replace-match "" t t format)))
  4575.   format)
  4576.  
  4577. (defun reftex-bibtex-selection-callback (data ignore no-revisit)
  4578.   ;; Callback function to be called from the BibTeX selection, in
  4579.   ;; order to display context.  This function is relatively slow and not
  4580.   ;; recommended for follow mode.  It works OK for individual lookups.
  4581.   (let ((win (selected-window))
  4582.         (key (reftex-get-bib-field "&key" data))
  4583.         bibfile-list item tmp)
  4584.  
  4585.     (catch 'exit
  4586.       (save-excursion
  4587.     (set-buffer reftex-call-back-to-this-buffer)
  4588.     (cond
  4589.      ((assq 'bib (symbol-value reftex-docstruct-symbol))
  4590.       (setq bibfile-list (reftex-get-bibfile-list)))
  4591.      ((setq tmp (assq 'thebib (symbol-value reftex-docstruct-symbol)))
  4592.       (setq bibfile-list (list (cdr tmp))
  4593.         item t))
  4594.      (reftex-default-bibliography
  4595.       (setq bibfile-list reftex-default-bibliography))
  4596.      (t (ding) (throw 'exit))))
  4597.  
  4598.       (when no-revisit
  4599.     (setq bibfile-list 
  4600.           (delq nil (mapcar (lambda (x)
  4601.                   (if (get-file-buffer x) x nil))
  4602.                 bibfile-list))))
  4603.  
  4604.       (reftex-pop-to-bibtex-entry 
  4605.        key bibfile-list (not reftex-keep-temporary-buffers) t item))
  4606.  
  4607.     (select-window win)))
  4608.  
  4609. ;;; ===========================================================================
  4610. ;;;
  4611. ;;; Here is the routine used for selection
  4612.  
  4613. ;; Marker for return point from recursive edit
  4614. (defvar reftex-recursive-edit-marker (make-marker))
  4615.  
  4616. (defvar reftex-last-data nil)
  4617. (defvar reftex-last-line nil)
  4618.  
  4619. (defun reftex-check-recursive-edit ()
  4620.   ;; Check if we are already in a recursive edit.  Abort with helpful
  4621.   ;; message if so.
  4622.   (if (marker-position reftex-recursive-edit-marker)
  4623.       (error
  4624.        (substitute-command-keys
  4625.         "In unfinished recursive edit. Finish (\\[exit-recursive-edit]) or abort (\\[abort-recursive-edit])."))))
  4626.  
  4627. (defun reftex-select-item (prompt help-string keymap
  4628.                   &optional offset
  4629.                   call-back cb-flag match-everywhere)
  4630. ;; Select an item, using PROMPT. The function returns a key indicating
  4631. ;; an exit status, along with a data structure indicating which item was
  4632. ;; selected.
  4633. ;; HELP-STRING contains help.  KEYMAP is a keymap with the available
  4634. ;; selection commands.
  4635. ;; OFFSET can be a label list item which will be selected at start.
  4636. ;; When it is t, point will start out at the beginning of the buffer.
  4637. ;; Any other value will cause restart where last selection left off.
  4638. ;; When CALL-BACK is given, it is a function which is called with the index
  4639. ;; of the element.
  4640. ;; CB-FLAG is the initial value of that flag.
  4641. ;; When MATCH-EVERYWHERE is t, searches will also match in non-selectable
  4642. ;; places.
  4643.  
  4644.   (let* (key-sq b e ev data last-data cmd skip-callback
  4645.         (orig-buffer (current-buffer))
  4646.         (search-str "") last-cmd callback-fwd)
  4647.  
  4648.     (setq ev
  4649.           (catch 'exit
  4650.             (save-window-excursion
  4651.               (setq truncate-lines t)
  4652.  
  4653.           ;; Find a good starting point
  4654.           (cond
  4655.            (offset
  4656.         (goto-char
  4657.          (or (and (listp offset)
  4658.               (text-property-any (point-min) (point-max)
  4659.                          ':data offset))
  4660.              (and (local-variable-p 'reftex-last-data (current-buffer))
  4661.               (boundp 'reftex-last-data)
  4662.               (listp reftex-last-data)
  4663.               (text-property-any (point-min) (point-max)
  4664.                          ':data reftex-last-data))
  4665.              (and (local-variable-p 'reftex-last-line (current-buffer))
  4666.               (boundp 'reftex-last-line)
  4667.               (integerp reftex-last-line)
  4668.               (progn (goto-line reftex-last-line) (point)))
  4669.              (point-min))))
  4670.            (t (goto-char (point-min))))
  4671.               (beginning-of-line 1)
  4672.  
  4673.       (unwind-protect
  4674.       (progn
  4675.         (use-local-map keymap)
  4676.         (while t
  4677.           (setq data (get-text-property (point) ':data))
  4678.           (setq last-data (or data last-data))
  4679.  
  4680.           (if (and data cb-flag call-back (not skip-callback))
  4681.           (funcall call-back data callback-fwd 
  4682.                (not reftex-revisit-to-follow)))
  4683.           (setq skip-callback nil)
  4684.           (if data
  4685.           (setq b (or (previous-single-property-change
  4686.                    (1+ (point)) ':data)
  4687.                   (point-min))
  4688.             e (or (next-single-property-change
  4689.                    (point) ':data)
  4690.                   (point-max)))
  4691.         (setq b (point) e (point)))
  4692.           (reftex-highlight 1 b e)
  4693.           (if (or (not (pos-visible-in-window-p b))
  4694.               (not (pos-visible-in-window-p e)))
  4695.           (recenter (/ (window-height) 2)))
  4696.           
  4697.           (setq last-cmd cmd
  4698.             cmd nil)
  4699.  
  4700.           (setq key-sq (read-key-sequence prompt))
  4701.           (setq cmd (lookup-key keymap key-sq))
  4702.  
  4703.           (reftex-unhighlight 2)
  4704.           (reftex-unhighlight 1)
  4705.           (reftex-unhighlight 0)
  4706.  
  4707.           (if cmd
  4708.           (condition-case nil
  4709.               (progn
  4710.             (command-execute cmd)
  4711.             ;FIXME: (run-hooks 'post-command-hook)
  4712.             )
  4713.             (error (ding)))
  4714.         (ding))
  4715.  
  4716.           (unless (equal (current-buffer) orig-buffer)
  4717.         (error "Selection commands must return to *RefTeX Select* buffer."))))
  4718.     (use-local-map nil)))))
  4719.  
  4720.     (set (make-local-variable 'reftex-last-line)
  4721.      (+ (count-lines (point-min) (point)) (if (bolp) 1 0)))
  4722.     (set (make-local-variable 'reftex-last-data) last-data)
  4723.     (and (get-buffer "*RefTeX Help*") (kill-buffer "*RefTeX Help*"))
  4724.     (message "")
  4725.     (list ev data last-data)))
  4726.  
  4727. ;; The following variables are all bound dynamically in `reftex-select-item'.
  4728. ;; The defvars are here only to silence the byte compiler.
  4729.  
  4730. (defvar last-cmd)
  4731. (defvar found-list)
  4732. (defvar cb-flag)
  4733. (defvar data)
  4734. (defvar call-back)
  4735. (defvar help-string)
  4736. (defvar skip-callback)
  4737. (defvar search-str)
  4738. (defvar match-everywhere)
  4739. (defvar forward)
  4740. (defvar keymap)
  4741. (defvar callback-fwd)
  4742. (defvar varioref)
  4743. (defconst reftex-select-search-minibuffer-map
  4744.   (let ((map (copy-keymap minibuffer-local-map)))
  4745.     (define-key map "\C-s"
  4746.       (function (lambda() (interactive) (setq forward t) (exit-minibuffer))))
  4747.     (define-key map "\C-r"
  4748.       (function (lambda() (interactive) (setq forward nil) (exit-minibuffer))))
  4749.     (define-key map "\C-m" 'exit-minibuffer)
  4750.     map))
  4751.  
  4752. ;; The selection commands
  4753.  
  4754. (defun reftex-select-next ()
  4755.   (interactive)
  4756.   (setq callback-fwd t)
  4757.   (or (eobp) (forward-char 1))
  4758.   (re-search-forward "^[^. \t\n\r]" nil t 1)
  4759.   (beginning-of-line 1))
  4760. (defun reftex-select-previous ()
  4761.   (interactive)
  4762.   (setq callback-fwd nil)
  4763.   (re-search-backward "^[^. \t\n\r]" nil t))
  4764. (defun reftex-select-scroll-up ()
  4765.   (interactive)
  4766.   (setq callback-fwd t)
  4767.   (while (and (pos-visible-in-window-p)
  4768.           (re-search-forward "^[^. \t\n\r]" nil t)))
  4769.   (beginning-of-line 1)
  4770.   (recenter 1))
  4771. (defun reftex-select-scroll-down ()
  4772.   (interactive)
  4773.   (setq callback-fwd nil)
  4774.   (while (and (pos-visible-in-window-p)
  4775.           (re-search-backward "^[^. \t\n\r]" nil t)))
  4776.   (recenter (- (window-height) 4)))
  4777. (defun reftex-select-next-heading ()
  4778.   (interactive)
  4779.   (end-of-line)
  4780.   (re-search-forward "^ " nil t)
  4781.   (beginning-of-line))
  4782. (defun reftex-select-previous-heading ()
  4783.   (interactive)
  4784.   (re-search-backward "^ " nil t))
  4785. (defun reftex-select-scroll-other-window ()
  4786.   (interactive)
  4787.   (setq skip-callback t)
  4788.   (scroll-other-window))
  4789. (defun reftex-select-scroll-other-window-down ()
  4790.   (interactive)
  4791.   (setq skip-callback t)
  4792.   (scroll-other-window-down nil))
  4793. (defun reftex-select-quit ()
  4794.   (interactive)
  4795.   (throw 'exit nil))
  4796. (defun reftex-select-jump-to-previous ()
  4797.   (interactive)
  4798.   (let (pos)
  4799.     (cond
  4800.      ((and (local-variable-p 'reftex-last-data (current-buffer))
  4801.        reftex-last-data
  4802.        (setq pos (text-property-any (point-min) (point-max)
  4803.                     ':data reftex-last-data)))
  4804.       (goto-char pos))
  4805.      ((and (local-variable-p 'reftex-last-line (current-buffer))
  4806.        (integerp reftex-last-line))
  4807.       (goto-line reftex-last-line))
  4808.      (t (ding)))))
  4809. (defun reftex-select-toggle-follow ()
  4810.   (interactive)
  4811.   (setq cb-flag (not cb-flag)))
  4812. (defun reftex-select-toggle-varioref ()
  4813.   (interactive)
  4814.   (if (string= varioref "\\ref")
  4815.       (setq varioref "\\vref")
  4816.     (setq varioref "\\ref"))
  4817.   (force-mode-line-update))
  4818. (defun reftex-select-callback ()
  4819.   (interactive)
  4820.   (if data (funcall call-back data callback-fwd nil) (ding)))
  4821. (defun reftex-select-accept ()
  4822.   (interactive)
  4823.   (throw 'exit 'return))
  4824. (defun reftex-select-read-label ()
  4825.   (interactive)
  4826.   (let ((label (completing-read 
  4827.         "Label: " (symbol-value reftex-docstruct-symbol)
  4828.         nil nil reftex-prefix)))
  4829.     (unless (or (equal label "") (equal label reftex-prefix))
  4830.       (throw 'exit label))))
  4831. (defun reftex-select-read-cite ()
  4832.   (interactive)
  4833.   (let* ((list (mapcar (lambda (x) 
  4834.              (cons (reftex-get-bib-field "&key" x) 1))
  4835.                found-list))
  4836.      (key (completing-read "Citation key: " list)))
  4837.     (unless (equal key "")
  4838.       (throw 'exit key))))
  4839. (defun reftex-select-help ()
  4840.   (interactive)
  4841.   (with-output-to-temp-buffer "*RefTeX Help*"
  4842.     (princ help-string))
  4843.   (reftex-enlarge-to-fit "*RefTeX Help*" t)
  4844.   (setq skip-callback t))
  4845. (defun reftex-select-recursive-edit ()
  4846.   (interactive)
  4847.   (set-marker reftex-recursive-edit-marker (point))
  4848.   (unwind-protect
  4849.       (progn
  4850.     (save-window-excursion
  4851.       (save-excursion
  4852.         (other-window 1)
  4853.         (message
  4854.          (substitute-command-keys
  4855.           "Recursive edit.  Return to selection with \\[exit-recursive-edit]"))
  4856.         (recursive-edit)))
  4857.     (unless (equal (marker-buffer
  4858.             reftex-recursive-edit-marker)
  4859.                (current-buffer))
  4860.       (error "Cannot continue RefTeX from this buffer."))
  4861.     (goto-char reftex-recursive-edit-marker))
  4862.     (set-marker reftex-recursive-edit-marker nil)))
  4863.  
  4864. (defun reftex-select-search-forward ()
  4865.   (interactive)
  4866.   (reftex-select-search t))
  4867. (defun reftex-select-search-backward ()
  4868.   (interactive)
  4869.   (reftex-select-search nil))
  4870. (defun reftex-select-search (forward)
  4871.   (let (tmp search-start matched)
  4872.     (if (or (and (not (eq last-cmd 'reftex-select-search-forward))
  4873.          (not (eq last-cmd 'reftex-select-search-backward)))
  4874.         (string= search-str ""))
  4875.     (setq tmp                ; get a new string
  4876.           (read-from-minibuffer
  4877.            (if (string= search-str "")
  4878.            "Search: "
  4879.          (format "Search [%s]:" search-str))
  4880.            nil reftex-select-search-minibuffer-map)
  4881.           search-str (if (string= tmp "")
  4882.                  search-str tmp)))
  4883.     (setq search-start (point))
  4884.     (and (not (string= search-str ""))
  4885.      (progn
  4886.        (while
  4887.            (and (setq matched
  4888.               (if forward
  4889.                   (search-forward search-str nil 1)
  4890.                 (search-backward search-str nil 1)))
  4891.             (or (>= (save-excursion
  4892.                   (goto-char (match-beginning 0))
  4893.                   (current-column))
  4894.                 (window-width))
  4895.             (not (or (get-text-property (point) ':data)
  4896.                  match-everywhere)))))
  4897.        (if matched
  4898.            (reftex-highlight 2 (match-beginning 0)
  4899.                  (match-end 0))
  4900.          (ding)
  4901.          (goto-char search-start))))))
  4902.  
  4903. ;;; ===========================================================================
  4904. ;;;
  4905. ;;; View cross references
  4906.  
  4907. (defun reftex-view-crossref (&optional arg)
  4908.   "View cross reference of \\ref or \\cite macro at point.
  4909. If the macro at point is a \\ref, show the corresponding label definition.
  4910. If it is a \\cite, show the BibTeX database entry or the \\bibitem.
  4911. If there is no such macro at point, search forward to find one.
  4912. When you call this function several times in direct succession, point will
  4913. move to view subsequent cross references further down in the buffer.
  4914. To cope with the plethora of variations in packages, this function
  4915. assumes any macro either starting with or ending in `ref' or `cite' to
  4916. contain cross references.
  4917. When the LaTeX package `xr' is being used, this command will also view
  4918. crossreferences in external documents.  However, this works correctly only
  4919. when the \\externaldocument macros are used with the optional label prefix
  4920. argument.
  4921. With one or two C-u prefixes, enforce rescanning of the document.
  4922. With argument t or 1, select the window showing the cross reference."
  4923.  
  4924.   (interactive "P")
  4925.  
  4926.   ;; See where we are.
  4927.   (let* ((re "\\\\\\([a-z]*\\(cite\\|ref\\)\\|\\(cite\\|ref\\)[a-z]*\\)\\**\\(\\[[^{}]*\\]\\)?{")
  4928.          (macro (car (car (reftex-what-macro t))))
  4929.          (this-word (reftex-this-word "*a-zA-Z\\\\"))
  4930.          (my-window (selected-window))
  4931.          pop-window cmd args point)
  4932.  
  4933.     (if (and macro
  4934.              (string-match "\\`\\\\cite\\|\\`\\\\ref\\|cite\\'\\|ref\\'"
  4935.                            macro))
  4936.         (and (setq macro (match-string 0 macro))
  4937.              (string-match "\\`\\\\" macro)
  4938.              (setq macro (substring macro 1)))
  4939.       (setq macro nil))
  4940.  
  4941.     (if (and macro 
  4942.          (eq last-command this-command)
  4943.          (eq last-command 'reftex-view-crossref))
  4944.         (if (string= macro "cite")
  4945.             (progn
  4946.               (skip-chars-forward "^},%")
  4947.               (while (and (eq (following-char) ?%)
  4948.                           (or (beginning-of-line 2) t)
  4949.                           (skip-chars-forward " \t\n\r")))
  4950.               (skip-chars-forward ",")
  4951.               (if (eq (following-char) ?})
  4952.                   (setq macro nil)))
  4953.           (setq macro nil)))
  4954.  
  4955.     (if (and (not macro)
  4956.              (or (not (string-match "\\`\\\\" this-word))
  4957.          (eq (following-char) ?\\)
  4958.                  (search-backward "\\" nil t)
  4959.                  t))
  4960.     (if (interactive-p)
  4961.         ;; Only move far if this function was called directly
  4962.         (and (re-search-forward re nil t)
  4963.          (setq macro (or (match-string 2) (match-string 3))))
  4964.       ;; The macro needs to be at point
  4965.       (and (looking-at re)
  4966.            (setq macro (or (match-string 2) (match-string 3)))
  4967.            (goto-char (match-end 0)))))
  4968.          
  4969.  
  4970.     (unless macro
  4971.       (error "No cross reference to display"))
  4972.  
  4973.     ;; Ensure access to scanning info
  4974.     (reftex-access-scan-info current-prefix-arg)
  4975.  
  4976.     (cond
  4977.      ((string= macro "cite")
  4978.       (cond
  4979.        ((assq 'bib (symbol-value reftex-docstruct-symbol))
  4980.     (setq cmd 'reftex-pop-to-bibtex-entry
  4981.           args (list
  4982.             (reftex-this-word "^{},%\n\r")
  4983.             (reftex-get-bibfile-list) nil t)))
  4984.        ((assq 'thebib (symbol-value reftex-docstruct-symbol))
  4985.     (setq cmd 'reftex-pop-to-bibtex-entry
  4986.           args (list 
  4987.             (reftex-this-word "^{},%\n\r")
  4988.             (list (cdr (assq 'thebib 
  4989.                      (symbol-value reftex-docstruct-symbol))))
  4990.             nil t t)))
  4991.        (t (error "Cannot display crossref\n"))))
  4992.      ((string= macro "ref")
  4993.       (let* ((label (reftex-this-word "^{}%\n\r"))
  4994.          (xr-data (assoc 'xr (symbol-value reftex-docstruct-symbol)))
  4995.          (xr-re (nth 2 xr-data))
  4996.              (entry (assoc label (symbol-value reftex-docstruct-symbol))))
  4997.  
  4998.     (if (and (not entry) (string-match xr-re label))
  4999.         ;; Label is defined in external document
  5000.         (save-excursion
  5001.           (save-match-data
  5002.         (set-buffer 
  5003.          (or (reftex-get-file-buffer-force
  5004.               (cdr (assoc (match-string 1 label) (nth 1 xr-data))))
  5005.              (error "Problem with external label %s" label))))
  5006.           (setq label (substring label (match-end 1)))
  5007.           (reftex-access-scan-info)
  5008.           (setq entry 
  5009.             (assoc label (symbol-value reftex-docstruct-symbol)))))
  5010.     (if entry
  5011.         (setq cmd 'reftex-pop-to-label
  5012.                   args (list label (list (nth 3 entry)) nil t))        
  5013.           (error "Label %s not known - reparse document might help" label))))
  5014.      (t (error "This should not happen (reftex-view-crossref)")))
  5015.     (setq point (point))
  5016.     (apply cmd args)
  5017.     (setq pop-window (selected-window))
  5018.     (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
  5019.     (select-window my-window)
  5020.     (goto-char point)
  5021.     (when (or (equal arg t) (equal arg 1))
  5022.       (select-window pop-window))))
  5023.  
  5024. (defun reftex-mouse-view-crossref (ev)
  5025.   "View cross reference of \\ref or \\cite macro where you click.
  5026. If the macro at point is a \\ref, show the corresponding label definition.
  5027. If it is a \\cite, show the BibTeX database entry.
  5028. If there is no such macro at point, search forward to find one.
  5029. With argument, actually select the window showing the cross reference."
  5030.   (interactive "e")
  5031.   (mouse-set-point ev)
  5032.   (reftex-view-crossref current-prefix-arg))
  5033.  
  5034. ;;; ===========================================================================
  5035. ;;;
  5036. ;;; Functions that check out the surroundings
  5037.  
  5038. (defun reftex-what-macro (which &optional bound)
  5039.   ;; Find out if point is within the arguments of any TeX-macro.
  5040.   ;; The return value is either ("\\macro" . (point)) or a list of them.
  5041.  
  5042.   ;; If WHICH is nil, immediately return nil.
  5043.   ;; If WHICH is t, return list of all macros enclosing point.
  5044.   ;; If WHICH is a list of macros, look only for those macros and return the
  5045.   ;;    name of the first macro in this list found to enclose point.
  5046.   ;; If the optional BOUND is an integer, bound backwards directed
  5047.   ;;    searches to this point.  If it is nil, limit to nearest \section -
  5048.   ;;    like statement.
  5049.  
  5050.   ;; This function is pretty stable, but can be fooled if the text contains
  5051.   ;; things like \macro{aa}{bb} where \macro is defined to take only one
  5052.   ;; argument.  As RefTeX cannot know this, the string "bb" would still be
  5053.   ;; considered an argument of macro \macro.
  5054.  
  5055.   (catch 'exit
  5056.     (if (null which) (throw 'exit nil))
  5057.     (let ((bound (or bound (save-excursion (re-search-backward
  5058.                                             reftex-section-regexp nil 1)
  5059.                                            (point))))
  5060.           pos cmd-list cmd cnt cnt-opt entry)
  5061.       (save-restriction
  5062.         (save-excursion
  5063.           (narrow-to-region (max 1 bound) (point-max))
  5064.           ;; move back out of the current parenthesis
  5065.           (while (condition-case nil
  5066.                      (progn (up-list -1) t)
  5067.                    (error nil))
  5068.             (setq cnt 1 cnt-opt 0)
  5069.             ;; move back over any touching sexps
  5070.             (while (and (reftex-move-to-previous-arg bound)
  5071.             (condition-case nil
  5072.                 (progn (backward-sexp) t)
  5073.               (error nil)))
  5074.           (if (eq (following-char) ?\[) (incf cnt-opt))
  5075.               (incf cnt))
  5076.             (setq pos (point))
  5077.             (when (and (or (= (following-char) ?\[)
  5078.                            (= (following-char) ?\{))
  5079.                        (re-search-backward "\\\\[*a-zA-Z]+\\=" nil t))
  5080.               (setq cmd (reftex-match-string 0))
  5081.           (when (looking-at "\\\\begin{[^}]*}")
  5082.         (setq cmd (reftex-match-string 0)
  5083.               cnt (1- cnt)))
  5084.           ;; This does ignore optional arguments.  Very hard to fix.
  5085.           (when (setq entry (assoc cmd reftex-env-or-mac-alist))
  5086.         (if (> cnt (or (nth 4 entry) 100))
  5087.             (setq cmd nil)))
  5088.               (cond
  5089.            ((null cmd))
  5090.            ((eq t which)
  5091.         (push (cons cmd (point)) cmd-list))
  5092.            ((member cmd which)
  5093.         (throw 'exit (cons cmd (point))))))
  5094.             (goto-char pos)))
  5095.         (nreverse cmd-list)))))
  5096.  
  5097. (defun reftex-what-environment (which &optional bound)
  5098.   ;; Find out if point is inside a LaTeX environment.
  5099.   ;; The return value is (e.g.) either ("equation" . (point)) or a list of
  5100.   ;; them.
  5101.  
  5102.   ;; If WHICH is nil, immediately return nil.
  5103.   ;; If WHICH is t, return list of all environments enclosing point.
  5104.   ;; If WHICH is a list of environments, look only for those environments and
  5105.   ;;   return the name of the first environment in this list found to enclose
  5106.   ;;   point.
  5107.  
  5108.   ;; If the optional BOUND is an integer, bound backwards directed searches to
  5109.   ;; this point.  If it is nil, limit to nearest \section - like statement.
  5110.  
  5111.   (catch 'exit
  5112.     (save-excursion
  5113.       (if (null which) (throw 'exit nil))
  5114.       (let ((bound (or bound (save-excursion (re-search-backward
  5115.                                               reftex-section-regexp nil 1)
  5116.                                              (point))))
  5117.             env-list end-list env)
  5118.         (while (re-search-backward "\\\\\\(begin\\|end\\){\\([^}]+\\)}"
  5119.                                    bound t)
  5120.           (setq env (buffer-substring-no-properties
  5121.                      (match-beginning 2) (match-end 2)))
  5122.           (cond
  5123.            ((string= (match-string 1) "end")
  5124.             (add-to-list 'end-list env))
  5125.            ((member env end-list)
  5126.             (setq end-list (delete env end-list)))
  5127.            ((eq t which)
  5128.             (push (cons env (point)) env-list))
  5129.            ((member env which)
  5130.             (throw 'exit (cons env (point))))))
  5131.         (nreverse env-list)))))
  5132.  
  5133. ;; ============================================================================
  5134. ;;
  5135. ;; Some generally useful functions
  5136.  
  5137. (defun reftex-no-props (string)
  5138.   ;; Return STRING with all text properties removed
  5139.   (and (stringp string)
  5140.        (set-text-properties 0 (length string) nil string))
  5141.   string)
  5142.  
  5143. (defun reftex-match-string (n)
  5144.   ;; Match string without properties
  5145.   (when (match-beginning n)
  5146.     (buffer-substring-no-properties (match-beginning n) (match-end n))))
  5147.  
  5148. (defun reftex-kill-buffer (buffer)
  5149. ;; Kill buffer if it exists.
  5150.   (and (setq buffer (get-buffer buffer))
  5151.        (kill-buffer buffer)))
  5152.  
  5153. (defun reftex-erase-buffer (buffer)
  5154. ;; Erase buffer if it exists.
  5155.   (and (setq buffer (get-buffer buffer))
  5156.        (save-excursion
  5157.      (set-buffer buffer)
  5158.      (erase-buffer))))
  5159.  
  5160. (defun reftex-this-word (&optional class)
  5161.   ;; Grab the word around point.
  5162.   (setq class (or class "-a-zA-Z0-9:_/.*;|"))
  5163.   (save-excursion
  5164.     (buffer-substring-no-properties
  5165.      (progn (skip-chars-backward class) (point))
  5166.      (progn (skip-chars-forward  class) (point)))))
  5167.  
  5168. (defvar enable-multibyte-characters)
  5169. (defun reftex-truncate (string ncols &optional ellipses padding)
  5170.   ;; Truncate a string to NCHAR characters.  
  5171.   ;; Works fast with ASCII and correctly with Mule characters.
  5172.   ;; When ELLIPSES is non-nil, put three dots at the end of the string.
  5173.   (setq string
  5174.     (cond
  5175.      ((and (boundp 'enable-multibyte-characters)
  5176.            enable-multibyte-characters)
  5177.       (if (<= (string-width string) ncols)
  5178.           string
  5179.         (if ellipses
  5180.         (concat (truncate-string-to-width string (- ncols 3)) "...")
  5181.           (truncate-string-to-width string ncols))))
  5182.      (t
  5183.       (if (<= (length string) ncols)
  5184.           string
  5185.         (if ellipses
  5186.         (concat (substring string 0 (- ncols 3)) "...")
  5187.           (substring string 0 ncols))))))
  5188.   (if padding
  5189.       (format (format "%%-%ds" ncols) string)
  5190.     string))
  5191.  
  5192. (defun reftex-nearest-match (regexp &optional pos)
  5193.   ;; Find the nearest match of REGEXP.  Set the match data.
  5194.   ;; If POS is given, calculate distances relative to it.
  5195.   ;; Return nil if there is no match.
  5196.   (let ((start (point)) (pos (or pos (point))) match1 match2 match)
  5197.     (goto-char start)
  5198.     (when (re-search-backward regexp nil t)
  5199.       (setq match1 (match-data)))
  5200.     (goto-char start)
  5201.     (when (re-search-forward regexp nil t)
  5202.       (setq match2 (match-data)))
  5203.     (goto-char start)
  5204.     (setq match
  5205.           (cond
  5206.            ((not match1) match2)
  5207.            ((not match2) match1)
  5208.            ((< (abs (- pos (car match1))) (abs (- pos (car match2)))) match1)
  5209.            (t match2)))
  5210.     (if match (progn (store-match-data match) t) nil)))
  5211.  
  5212. (defun reftex-auto-mode-alist ()
  5213.   ;; Return an `auto-mode-alist' with only the .gz (etc) thingies.
  5214.   ;; Stolen from gnus nnheader.
  5215.   (let ((alist auto-mode-alist)
  5216.         out)
  5217.     (while alist
  5218.       (when (listp (cdr (car alist)))
  5219.         (push (car alist) out))
  5220.       (pop alist))
  5221.     (nreverse out)))
  5222.  
  5223. (defun reftex-enlarge-to-fit (buf2 &optional keep-current)
  5224.   ;; Enlarge other window displaying buffer without killing current window
  5225.   ;; If KEEP-CURRENT in non-nil, current buffer must remain visible.
  5226.   (let* ((win1 (selected-window))
  5227.      (buf1 (current-buffer))
  5228.      (win2 (get-buffer-window buf2)))
  5229.     (when win2
  5230.       (select-window win2)
  5231.       (unless (and (pos-visible-in-window-p 1)
  5232.            (pos-visible-in-window-p (point-max)))
  5233.     (enlarge-window (1+ (- (count-lines 1 (point-max))
  5234.                    (window-height))))))
  5235.     (cond
  5236.      ((window-live-p win1) (select-window win1))
  5237.      (keep-current
  5238.       ;; we must have the old buffer!
  5239.       (switch-to-buffer-other-window buf1)
  5240.       (shrink-window (- (window-height) window-min-height))))))
  5241.  
  5242. (defun reftex-access-search-path (which &optional recurse file)
  5243.   ;; Access path from environment variables. WHICH is either "tex" or "bib".
  5244.   ;; When RECURSE is t, expand recursive paths, ending in double slash.
  5245.   ;; FILE is just for the message.
  5246.   (let* ((pathvar (intern (concat "reftex-" which "-path")))
  5247.      (status (get pathvar 'status)))
  5248.     (cond
  5249.      ((eq status 'recursed))
  5250.      ((and status (null recurse)))
  5251.      ((null status)
  5252.       (let ((env-vars (if (equal which "tex") (list "TEXINPUTS")
  5253.             reftex-bibpath-environment-variables)))
  5254.     (set pathvar (reftex-parse-colon-path
  5255.                (mapconcat (function (lambda(x) (or (getenv x) "")))
  5256.                   env-vars path-separator))))
  5257.     (put pathvar 'status 'split))
  5258.      ((and (eq 'split status) recurse)
  5259.       (message "Expanding search path to find %s file: %s ..." which file)
  5260.       (set pathvar (reftex-expand-path (symbol-value pathvar)))
  5261.       (put pathvar 'status 'recursed)))))
  5262.  
  5263. (defun reftex-find-file-on-path (file path)
  5264.   ;; Find FILE along the directory list PATH.
  5265.   (catch 'exit
  5266.     (when (file-name-absolute-p file)
  5267.       (if (file-exists-p file)
  5268.       (throw 'exit file)
  5269.     (throw 'exit nil)))
  5270.     (let* ((thepath path) file1 dir 
  5271.        (doubleslash (concat "/" "/")))
  5272.       (while (setq dir (pop thepath))
  5273.     (when (string= (substring dir -2) doubleslash)
  5274.       (setq dir (substring dir 0 -1)))
  5275.     (setq file1 (expand-file-name file (expand-file-name dir)))
  5276.     (if (file-exists-p file1)
  5277.         (throw 'exit file1)))
  5278.       ;; No such file
  5279.       nil)))
  5280.  
  5281. (defun reftex-parse-colon-path (path)
  5282.   ;; Like parse-colon-parse, but // or /~ have no effects.
  5283.   (mapcar 'file-name-as-directory
  5284.       (delete "" (split-string path (concat path-separator "+")))))
  5285.  
  5286. (defun reftex-expand-path (path)
  5287.   ;; Expand parts of path ending in a double slash
  5288.   (let (path1 dir dirs (doubleslash (concat "/" "/")))
  5289.     (while (setq dir (pop path))
  5290.       (if (string= (substring dir -2) doubleslash)
  5291.       (progn
  5292.         (setq dir (substring dir 0 -1))
  5293.         (setq dirs (reftex-recursive-directory-list dir))
  5294.         (setq path1 (append dirs path1)))
  5295.     (push dir path1)))
  5296.     (nreverse path1)))
  5297.  
  5298. (defun reftex-recursive-directory-list (dir)
  5299.   (let ((path (list dir)) dirs path1)
  5300.     (while (setq dir (pop path))
  5301.       (setq dirs
  5302.       (delete nil 
  5303.         (mapcar 
  5304.          (function 
  5305.           (lambda (x)
  5306.             (if (and (file-directory-p x)
  5307.                  (not (string-match "/\\.+\\'" x)))
  5308.             (file-name-as-directory x)
  5309.           nil)))
  5310.             (directory-files dir t))))
  5311.       (setq path (append dirs path))
  5312.       (push dir path1))
  5313.     path1))
  5314.  
  5315. (defun reftex-make-regexp-allow-for-ctrl-m (string)
  5316.   ;; convert STRING into a regexp, allowing ^M for \n and vice versa
  5317.   (let ((start -2))
  5318.     (setq string (regexp-quote string))
  5319.     (while (setq start (string-match "[\n\r]" string (+ 3 start)))
  5320.       (setq string (replace-match "[\n\r]" nil t string)))
  5321.     string))
  5322.  
  5323. (defun reftex-make-desperate-section-regexp (old)
  5324.   ;; Return a regexp which will still match a section statement even if
  5325.   ;; x-symbol or isotex or the like have been at work in the mean time.
  5326.   (let* ((n (1+ (string-match "[[{]" old)))
  5327.          (new (regexp-quote (substring old 0 (1+ (string-match "[[{]" old)))))
  5328.          (old (substring old n)))
  5329.     (while (string-match
  5330.             "\\([\r\n]\\)\\|\\(\\`\\|[ \t\n\r]\\)\\([a-zA-Z0-9]+\\)\\([ \t\n\r]\\|}\\'\\)"
  5331.             old)
  5332.       (if (match-beginning 1)
  5333.           (setq new (concat new "[^\n\r]*[\n\r]"))
  5334.         (setq new (concat new "[^\n\r]*" (match-string 3 old))))
  5335.       (setq old (substring old (match-end 0))))
  5336.     new))
  5337.  
  5338. (defun reftex-delete-list (elt-list list)
  5339.   ;; like delete, but with a list of things to delete
  5340.   ;; (original code from Rory Molinari)
  5341.   (while elt-list
  5342.     (setq list (delete (car elt-list) list)
  5343.           elt-list (cdr elt-list)))
  5344.   list)
  5345.  
  5346. (defun reftex-get-buffer-visiting (file)
  5347.   ;; return a buffer visiting FILE
  5348.   (cond
  5349.    ((boundp 'find-file-compare-truenames) ; XEmacs
  5350.     (let ((find-file-compare-truenames t))
  5351.       (get-file-buffer file)))
  5352.    ((fboundp 'find-buffer-visiting)       ; Emacs
  5353.     (find-buffer-visiting file))
  5354.    (t (error "This should not happen (reftex-get-buffer-visiting)"))))
  5355.  
  5356. (defun reftex-get-file-buffer-force (file &optional mark-to-kill)
  5357.   ;; Return a buffer visiting file.  Make one, if necessary.
  5358.   ;; If neither such a buffer nor the file exist, return nil.
  5359.   ;; If MARK-TO-KILL is t and there is no live buffer, load the file with
  5360.   ;; initializations according to `reftex-initialize-temporary-buffers',
  5361.   ;; and mark the buffer to be killed after use.
  5362.  
  5363.   (let ((buf (reftex-get-buffer-visiting file)))
  5364.  
  5365.     (cond (buf
  5366.            ;; We have it already as a buffer - just return it
  5367.            buf)
  5368.  
  5369.           ((file-readable-p file)
  5370.            ;; At least there is such a file and we can read it.
  5371.  
  5372.            (if (or (not mark-to-kill)
  5373.                    (eq t reftex-initialize-temporary-buffers))
  5374.  
  5375.                ;; Visit the file with full magic
  5376.                (setq buf (find-file-noselect file))
  5377.  
  5378.              ;; Else: Visit the file just briefly, without or
  5379.              ;;       with limited Magic
  5380.  
  5381.              ;; The magic goes away
  5382.              (let ((format-alist nil)
  5383.                    (auto-mode-alist (reftex-auto-mode-alist))
  5384.                    (default-major-mode 'fundamental-mode)
  5385.                    (after-insert-file-functions nil))
  5386.                (setq buf (find-file-noselect file)))
  5387.  
  5388.              ;; Is there a hook to run?
  5389.              (when (listp reftex-initialize-temporary-buffers)
  5390.                (save-excursion
  5391.                  (set-buffer buf)
  5392.                  (run-hooks 'reftex-initialize-temporary-buffers))))
  5393.  
  5394.        ;; Lets see if we got a license to kill :-|
  5395.        (and mark-to-kill
  5396.         (add-to-list 'reftex-buffers-to-kill buf))
  5397.  
  5398.            ;; Return the new buffer
  5399.            buf)
  5400.  
  5401.           ;; If no such file exists, return nil
  5402.           (t nil))))
  5403.  
  5404. (defun reftex-splice-symbols-into-list (list alist)
  5405.   ;; Splice the association in ALIST of any symbols in LIST into the list.
  5406.   ;; Return new list.
  5407.   (let (rtn tmp)
  5408.     (while list
  5409.       (while (and (not (null (car list)))  ;; keep list elements nil
  5410.                   (symbolp (car list)))
  5411.         (setq tmp (car list))
  5412.         (cond
  5413.          ((assoc tmp alist)
  5414.           (setq list (append (nth 2 (assoc tmp alist)) (cdr list))))
  5415.          (t
  5416.           (error "Cannot treat symbol %s in reftex-label-alist"
  5417.                  (symbol-name tmp)))))
  5418.       (push (pop list) rtn))
  5419.     (nreverse rtn)))
  5420.  
  5421. (defun reftex-uniquify (alist &optional keep-list)
  5422.   ;; Return a list of all elements in ALIST, but each car only once.
  5423.   ;; Elements of KEEP-LIST are not removed even if duplicate.
  5424.   (let (new elm)
  5425.     (while alist
  5426.       (setq elm (pop alist))
  5427.       (if (or (member (car elm) keep-list)
  5428.               (not (assoc (car elm) new)))
  5429.           (push elm new)))
  5430.     (nreverse new)))
  5431.  
  5432. (defun reftex-use-fonts ()
  5433.   ;; Return t if we can and want to use fonts.
  5434.   (and window-system
  5435.        reftex-use-fonts
  5436.        (featurep 'font-lock)))
  5437.  
  5438. (defun reftex-refontify ()
  5439.   ;; Return t if we need to refontify context
  5440.   (and (reftex-use-fonts)
  5441.        (or (eq t reftex-refontify-context)
  5442.            (and (eq 1 reftex-refontify-context)
  5443.                 (or (featurep 'x-symbol))))))
  5444.  
  5445. (defun reftex-fontify-select-label-buffer ()
  5446.   ;; Fontify the `*RefTeX Select*' buffer
  5447.   (cond
  5448.    ((fboundp 'font-lock-default-fontify-region)
  5449.     ;; Good: we have the indirection functions, and can support lazy-lock etc.
  5450.     (set (make-local-variable 'font-lock-fontify-region-function)
  5451.      'reftex-select-font-lock-fontify-region)
  5452.     (let ((major-mode 'latex-mode))
  5453.       (font-lock-mode 1)))
  5454.    ((fboundp 'font-lock-set-defaults-1)
  5455.     ;; Looks like the XEmacs font-lock stuff.
  5456.     ;; FIXME: this is still kind of a hack, but might go away with XEmacs 20.4
  5457.     (set (make-local-variable 'font-lock-keywords) nil)
  5458.     (let ((major-mode 'latex-mode)
  5459.       (font-lock-defaults-computed nil))
  5460.       (font-lock-set-defaults-1)
  5461.       (reftex-select-font-lock-fontify-region (point-min) (point-max))))
  5462.    (t
  5463.     ;; Oops? 
  5464.     (message "Sorry: cannot refontify RefTeX Select buffer."))))
  5465.  
  5466. (defun reftex-select-font-lock-fontify-region (beg end &optional loudly)
  5467.   ;; Fontify a region, but only lines starting with a dot.
  5468.   (let ((func (if (fboundp 'font-lock-default-fontify-region)
  5469.           'font-lock-default-fontify-region
  5470.         'font-lock-fontify-region))
  5471.     beg1 end1)
  5472.     (goto-char beg)
  5473.     (while (re-search-forward "^\\." end t)
  5474.       (setq beg1 (point) end1 (progn (skip-chars-forward "^\n") (point)))
  5475.       (funcall func beg1 end1 nil)
  5476.       (goto-char end1))))
  5477.  
  5478. ;; Highlighting uses overlays.  If this is for XEmacs, we need to load
  5479. ;; the overlay library, available in version 19.15
  5480. (and (not (fboundp 'make-overlay))
  5481.      (condition-case nil
  5482.          (require 'overlay)
  5483.        (error
  5484.         (error "RefTeX needs overlay emulation (available in XEmacs 19.15)"))))
  5485.  
  5486. ;; We keep a vector with several different overlays to do our highlighting.
  5487. (defvar reftex-highlight-overlays [nil nil nil])
  5488.  
  5489. ;; Initialize the overlays
  5490. (aset reftex-highlight-overlays 0 (make-overlay 1 1))
  5491. (overlay-put (aref reftex-highlight-overlays 0) 'face 'highlight)
  5492. (aset reftex-highlight-overlays 1 (make-overlay 1 1))
  5493. (overlay-put (aref reftex-highlight-overlays 1) 'face 'highlight)
  5494. (aset reftex-highlight-overlays 2 (make-overlay 1 1))
  5495. (overlay-put (aref reftex-highlight-overlays 2) 'face
  5496.              (if (string-match "XEmacs" emacs-version) 'zmacs-region 'region))
  5497.  
  5498. ;; Two functions for activating and deactivation highlight overlays
  5499. (defun reftex-highlight (index begin end &optional buffer)
  5500.   "Highlight a region with overlay INDEX."
  5501.   (move-overlay (aref reftex-highlight-overlays index)
  5502.                 begin end (or buffer (current-buffer))))
  5503. (defun reftex-unhighlight (index)
  5504.   "Detach overlay INDEX."
  5505.   (delete-overlay (aref reftex-highlight-overlays index)))
  5506.  
  5507. (defun reftex-highlight-shall-die ()
  5508.   ;; Function used in pre-command-hook to remove highlights.
  5509.   (remove-hook 'pre-command-hook 'reftex-highlight-shall-die)
  5510.   (reftex-unhighlight 0))
  5511.  
  5512. ;;; ---------------------------------------------------------------------------
  5513. ;;;
  5514. ;;; Functions to compile the tables, reset the mode etc.
  5515.  
  5516. (defun reftex-reset-mode ()
  5517.   "Reset RefTeX Mode.  Required to implement changes to some list variables.
  5518. This function will compile the information in `reftex-label-alist' and similar
  5519. variables.  It is called when RefTeX is first used, and after changes to
  5520. these variables."
  5521.   (interactive)
  5522.  
  5523.   ;; Record that we have done this
  5524.   (setq reftex-tables-dirty nil)
  5525.   (setq reftex-memory 
  5526.     (list reftex-label-alist reftex-label-alist-external-add-ons
  5527.           reftex-default-label-alist-entries))
  5528.  
  5529.   ;; Reset the file search path variables
  5530.   (put 'reftex-tex-path 'status nil)
  5531.   (put 'reftex-bib-path 'status nil)
  5532.  
  5533.   ;; Kill temporary buffers associated with RefTeX - just in case they
  5534.   ;; were not cleaned up properly
  5535.   (save-excursion
  5536.     (let ((buffer-list '("*RefTeX Help*" "*RefTeX Select*"
  5537.              "*Duplicate Labels*" "*toc*" "*RefTeX-scratch*"))
  5538.       buf)
  5539.       (while (setq buf (pop buffer-list))
  5540.     (if (get-buffer buf)
  5541.         (kill-buffer buf))))
  5542.     (reftex-erase-all-selection-buffers))
  5543.  
  5544.   ;; Make sure the current document will be rescanned soon.
  5545.   (reftex-reset-scanning-information)
  5546.  
  5547.   ;; Plug functions into AUCTeX if the user option says so.
  5548.   (reftex-plug-into-AUCTeX)
  5549.  
  5550.   (message "updating internal tables...")
  5551.   (reftex-compute-ref-cite-tables)
  5552.   (message "updating internal tables... done"))
  5553.  
  5554. (defun reftex-reset-scanning-information ()
  5555.   "Reset the symbols containing information from buffer scanning.
  5556. This enforces rescanning the buffer on next use."
  5557.   (if (string= reftex-last-toc-master (reftex-TeX-master-file))
  5558.       (reftex-empty-toc-buffer))
  5559.   (let ((symlist reftex-multifile-symbols)
  5560.         symbol)
  5561.     (while symlist
  5562.       (setq symbol (car symlist)
  5563.             symlist (cdr symlist))
  5564.       (if (and (symbolp (symbol-value symbol))
  5565.                (not (null (symbol-value symbol))))
  5566.           (set (symbol-value symbol) nil)))))
  5567.  
  5568. (defun reftex-erase-all-selection-buffers ()
  5569.   ;; Remove all selection buffers associated with current document.
  5570.   (mapcar (function 
  5571.        (lambda (type)
  5572.          (reftex-erase-buffer (reftex-make-selection-buffer-name type))))
  5573.       reftex-typekey-list))
  5574.  
  5575. (defun reftex-compute-ref-cite-tables ()
  5576.   ;; Update ref and cite tables
  5577.  
  5578.   ;; Update AUCTeX style information
  5579.   (when (and (featurep 'tex-site) (fboundp 'TeX-update-style))
  5580.     (condition-case nil (TeX-update-style) (error nil)))
  5581.  
  5582.   ;; Compile information in reftex-label-alist
  5583.   (let ((tmp (reftex-uniquify (reftex-splice-symbols-into-list
  5584.                               (append
  5585.                                reftex-label-alist
  5586.                                reftex-label-alist-external-add-ons
  5587.                                reftex-default-label-alist-entries)
  5588.                               reftex-label-alist-builtin)
  5589.                              '(nil)))
  5590.         entry env-or-mac typekeychar typekey prefix context word
  5591.         fmt reffmt labelfmt wordlist qh-list macros-with-labels
  5592.         nargs nlabel opt-args cell sum i words-are-re)
  5593.  
  5594.     (setq reftex-words-to-typekey-alist nil
  5595.           reftex-typekey-list nil
  5596.           reftex-typekey-to-format-alist nil
  5597.           reftex-typekey-to-prefix-alist nil
  5598.           reftex-env-or-mac-alist nil
  5599.           reftex-label-env-list nil
  5600.           reftex-label-mac-list nil)
  5601.     (while tmp
  5602.       (catch 'next-entry
  5603.         (setq entry (car tmp)
  5604.               env-or-mac (car entry)
  5605.               entry (cdr entry)
  5606.               tmp (cdr tmp))
  5607.         (if (null env-or-mac)
  5608.             (setq env-or-mac ""))
  5609.         (if (stringp (car entry))
  5610.             ;; This is before version 2.00 - convert entry to new format
  5611.             ;; This is just to keep old users happy
  5612.             (setq entry (cons (string-to-char (car entry))
  5613.                               (cons (concat (car entry) ":")
  5614.                                     (cdr entry)))))
  5615.         (setq typekeychar (nth 0 entry)
  5616.               typekey (char-to-string typekeychar)
  5617.               prefix (nth 1 entry)
  5618.               fmt (nth 2 entry)
  5619.               context (nth 3 entry)
  5620.               wordlist (nth 4 entry))
  5621.         (if (stringp wordlist)
  5622.             ;; This is before version 2.04 - convert to new format
  5623.             (setq wordlist (nthcdr 4 entry)))
  5624.  
  5625.         (if (and (stringp fmt)
  5626.                  (string-match "@" fmt))
  5627.             ;; special syntax for specifying a label format
  5628.             (setq fmt (split-string fmt "@+"))
  5629.           (setq fmt (list "\\label{%s}" fmt)))
  5630.         (setq labelfmt (car fmt)
  5631.               reffmt (nth 1 fmt))
  5632.         (if typekey
  5633.             (add-to-list 'reftex-typekey-list typekey))
  5634.         (if (and typekey prefix
  5635.                  (not (assoc typekey reftex-typekey-to-prefix-alist)))
  5636.             (add-to-list 'reftex-typekey-to-prefix-alist
  5637.                          (cons typekey prefix)))
  5638.         (cond
  5639.          ((string-match "\\`\\\\" env-or-mac)
  5640.           ;; It's a macro
  5641.           (let ((result (reftex-parse-args env-or-mac)))
  5642.             (setq env-or-mac (or (first result) env-or-mac)
  5643.           nargs (second result)
  5644.                   nlabel (third result)
  5645.                   opt-args (fourth result))
  5646.             (if nlabel (add-to-list 'macros-with-labels env-or-mac)))
  5647.           (add-to-list 'reftex-label-mac-list env-or-mac))
  5648.          (t
  5649.           (setq nargs nil nlabel nil opt-args nil)
  5650.           (cond ((string= env-or-mac "any"))
  5651.                 ((string= env-or-mac ""))
  5652.                 ((string= env-or-mac "section"))
  5653.                 (t
  5654.                  (add-to-list 'reftex-label-env-list env-or-mac)))))
  5655.     ;; Translate some special context cases
  5656.     (when (assq context reftex-default-context-regexps)
  5657.       (setq context 
  5658.         (format 
  5659.          (cdr (assq context reftex-default-context-regexps))
  5660.          (regexp-quote env-or-mac))))
  5661.         (and reffmt
  5662.              (not (assoc typekey reftex-typekey-to-format-alist))
  5663.              (push (cons typekey reffmt) reftex-typekey-to-format-alist))
  5664.         (and (not (string= env-or-mac "any"))
  5665.              (not (string= env-or-mac ""))
  5666.              (not (assoc env-or-mac reftex-env-or-mac-alist))
  5667.              (push (list env-or-mac typekey context labelfmt
  5668.              nargs nlabel opt-args)
  5669.                    reftex-env-or-mac-alist))
  5670.     (if (eq (car wordlist) 'regexp)
  5671.         (setq wordlist (cdr wordlist)
  5672.           words-are-re t)
  5673.       (setq words-are-re nil))
  5674.         (while (and (setq word (pop wordlist))
  5675.                     (stringp word))
  5676.           (setq word (identity (if words-are-re word (regexp-quote word))))
  5677.           (or (assoc word reftex-words-to-typekey-alist)
  5678.               (push (cons word typekey) reftex-words-to-typekey-alist)))
  5679.         (cond
  5680.          ((string= "" env-or-mac) nil)
  5681.          ((setq cell (assoc typekey qh-list))
  5682.           (push env-or-mac (cdr cell)))
  5683.          (t
  5684.           (push (list typekey env-or-mac) qh-list)))))
  5685.  
  5686.     (setq qh-list 
  5687.       (sort qh-list (function 
  5688.              (lambda (x1 x2) (string< (car x1) (car x2))))))
  5689.     (setq reftex-typekey-to-prefix-alist
  5690.           (nreverse reftex-typekey-to-prefix-alist))
  5691.     (setq reftex-type-query-prompt
  5692.           (concat "Label type: "
  5693.                   (mapconcat (function (lambda(x) (format "[%s]" (car x))))
  5694.                              qh-list " ")
  5695.                   " (?=Help)"))
  5696.     (setq reftex-type-query-help
  5697.           (concat "SELECT A LABEL TYPE:\n--------------------\n"
  5698.                   (mapconcat
  5699.            (function
  5700.             (lambda(x)
  5701.              (setq sum 0)
  5702.              (format " [%s]   %s"
  5703.                  (car x)
  5704.                  (mapconcat
  5705.                   (lambda(x)
  5706.                 (setq sum (+ sum (length x)))
  5707.                 (if (< sum 60)
  5708.                     x
  5709.                   (setq sum 0)
  5710.                   (concat "\n       " x)))
  5711.                   (cdr x) " "))))
  5712.                    qh-list "\n")))
  5713.  
  5714.     ;; Convert magic words to regular expressions
  5715.     (setq reftex-words-to-typekey-alist
  5716.       (mapcar 
  5717.        (lambda (x)
  5718.          (setq word (car x)
  5719.            typekey (cdr x)
  5720.            fmt (cdr (assoc typekey reftex-typekey-to-format-alist)))
  5721.          (setq word (concat "\\W\\(" word "[ \t\n\r]*\\)\\("))
  5722.          (setq i 0)
  5723.          (while (and (< i 10)
  5724.              (< i (length fmt))
  5725.              (not (member (aref fmt i) '(?%))))
  5726.            (setq word (concat word "\\|" (regexp-quote
  5727.                           (substring fmt 0 (1+ i)))))
  5728.            (incf i))
  5729.          (cons (concat word "\\)\\=") typekey))
  5730.        (nreverse reftex-words-to-typekey-alist)))
  5731.  
  5732.     ;; Calculate the regular expressions
  5733.     (let ((label-re "\\\\label{\\([^}]*\\)}")
  5734.           (include-re "\\(\\`\\|[\n\r]\\)[ \t]*\\\\\\(include\\|input\\)[{ \t]+\\([^} \t\n\r]+\\)")
  5735.           (section-re
  5736.            (concat "\\(\\`\\|[\n\r]\\)[ \t]*\\\\\\("
  5737.                   (mapconcat 'car reftex-section-levels "\\|")
  5738.                   "\\)\\*?\\(\\[[^]]*\\]\\)?{"))
  5739.       (appendix-re "\\(\\`\\|[\n\r]\\)[ \t]*\\(\\\\appendix\\)")
  5740.           (macro-re
  5741.            (if macros-with-labels
  5742.                (concat "\\("
  5743.                        (mapconcat 'regexp-quote macros-with-labels "\\|")
  5744.                        "\\)[[{]")
  5745.              ""))
  5746.           (find-label-re-format
  5747.            (concat "\\("
  5748.            (mapconcat 'regexp-quote (append '("\\label")
  5749.                             macros-with-labels) "\\|")
  5750.                    "\\)\\([[{][^]}]*[]}]\\)*[[{]\\(%s\\)[]}]")))
  5751.       (setq reftex-section-regexp section-re
  5752.             reftex-section-or-include-regexp
  5753.             (concat section-re "\\|" include-re)
  5754.             reftex-everything-regexp
  5755.             (concat label-re "\\|" section-re "\\|" include-re
  5756.             "\\|" appendix-re
  5757.                     (if macros-with-labels "\\|" "") macro-re)
  5758.             reftex-find-label-regexp-format find-label-re-format
  5759.         reftex-find-label-regexp-format2 
  5760.         "\\([]} \t\n\r]\\)\\([[{]\\)\\(%s\\)[]}]"))))
  5761.  
  5762. ;;; Keybindings --------------------------------------------------------------
  5763.  
  5764. (define-key reftex-mode-map  "\C-c="     'reftex-toc)
  5765. (define-key reftex-mode-map  "\C-c("     'reftex-label)
  5766. (define-key reftex-mode-map  "\C-c)"     'reftex-reference)
  5767. (define-key reftex-mode-map  "\C-c["     'reftex-citation)
  5768. (define-key reftex-mode-map  "\C-c&"     'reftex-view-crossref)
  5769.  
  5770. ;; If the user requests so, she can have a few more bindings:
  5771. (cond
  5772.  (reftex-extra-bindings
  5773.   (define-key reftex-mode-map  "\C-ct"     'reftex-toc)
  5774.   (define-key reftex-mode-map  "\C-cl"     'reftex-label)
  5775.   (define-key reftex-mode-map  "\C-cr"     'reftex-reference)
  5776.   (define-key reftex-mode-map  "\C-cc"     'reftex-citation)
  5777.   (define-key reftex-mode-map  "\C-cv"     'reftex-view-crossref)
  5778.   (define-key reftex-mode-map  "\C-cg"     'reftex-grep-document)
  5779.   (define-key reftex-mode-map  "\C-cs"     'reftex-search-document)))
  5780.  
  5781. ;; Selection Keymaps
  5782. (let ((map (make-sparse-keymap)))
  5783.   ; First, the common stuff
  5784.   (substitute-key-definition
  5785.    'next-line 'reftex-select-next               map global-map)
  5786.   (substitute-key-definition
  5787.    'previous-line 'reftex-select-previous           map global-map)
  5788.   (substitute-key-definition
  5789.    'scroll-up 'reftex-select-scroll-up               map global-map)
  5790.   (substitute-key-definition
  5791.    'scroll-down 'reftex-select-scroll-down           map global-map)
  5792.   (substitute-key-definition
  5793.    'scroll-other-window 'reftex-select-scroll-other-window map global-map)
  5794.   (substitute-key-definition
  5795.    'scroll-other-window-down 'reftex-select-scroll-other-window-down map global-map)
  5796.   (substitute-key-definition
  5797.    'beginning-of-buffer 'beginning-of-buffer           map global-map)
  5798.   (substitute-key-definition
  5799.    'end-of-buffer 'end-of-buffer               map global-map)
  5800.   (substitute-key-definition
  5801.    'keyboard-quit 'keyboard-quit                       map global-map)
  5802.   (substitute-key-definition
  5803.    'newline 'reftex-select-accept               map global-map)
  5804.   (substitute-key-definition
  5805.    'delete-other-windows 'delete-other-windows           map global-map)
  5806.   (define-key map " "        'reftex-select-callback)
  5807.   (define-key map "n"        'reftex-select-next)
  5808.   (define-key map [(down)]   'reftex-select-next)
  5809.   (define-key map "p"        'reftex-select-previous)
  5810.   (define-key map [(up)]     'reftex-select-previous)
  5811.   (define-key map "f"        'reftex-select-toggle-follow)
  5812.   (define-key map "\C-m"     'reftex-select-accept)
  5813.   (define-key map [(return)] 'reftex-select-accept) 
  5814.   (define-key map "\C-s"     'reftex-select-search-forward)
  5815.   (define-key map "\C-r"     'reftex-select-search-backward)
  5816.   (define-key map "e"        'reftex-select-recursive-edit)
  5817.   (define-key map "q"        'reftex-select-quit)
  5818.   (define-key map "?"        'reftex-select-help)
  5819.  
  5820.   (setq reftex-select-label-map map)
  5821.   (setq reftex-select-bib-map (copy-keymap map))
  5822.  
  5823.   ;; Now the rest
  5824.  
  5825.   (loop for key across "cgilrRstx#%" do
  5826.     (define-key reftex-select-label-map (vector (list key))
  5827.       (list 'lambda '() '(interactive) (list 'throw '(quote exit) key))))
  5828.   (define-key reftex-select-label-map "b"     'reftex-select-jump-to-previous)
  5829.   (define-key reftex-select-label-map "v"     'reftex-select-toggle-varioref)
  5830.   (define-key reftex-select-label-map [(tab)] 'reftex-select-read-label)
  5831.   (define-key reftex-select-label-map "\C-i"  'reftex-select-read-label)
  5832.   (define-key reftex-select-label-map "\C-c\C-n" 'reftex-select-next-heading)
  5833.   (define-key reftex-select-label-map "\C-c\C-p" 'reftex-select-previous-heading)
  5834.  
  5835.   (loop for key across "grRa" do
  5836.     (define-key reftex-select-bib-map (vector (list key))
  5837.       (list 'lambda '() '(interactive) (list 'throw '(quote exit) key))))
  5838.   (define-key reftex-select-bib-map "\C-i" 'reftex-select-read-cite)
  5839.   (define-key reftex-select-bib-map [(tab)] 'reftex-select-read-cite))
  5840.  
  5841. ;; Table of Contents map
  5842. (let ((map reftex-toc-map))
  5843.   (define-key map  [(mouse-2)] 'reftex-toc-mouse-goto-line-and-hide); Emacs
  5844.   (define-key map  [(button2)] 'reftex-toc-mouse-goto-line-and-hide); XEmacs
  5845.   (define-key map  "n"         'next-line)
  5846.   (define-key map  "p"         'previous-line)
  5847.   (define-key map  "?"         'reftex-toc-show-help)
  5848.   (define-key map  " "         'reftex-toc-view-line)
  5849.   (define-key map  "\C-m"      'reftex-toc-goto-line-and-hide)
  5850.   (define-key map  "\C-i"      'reftex-toc-goto-line)
  5851.   (define-key map  "r"         'reftex-toc-rescan)
  5852.   (define-key map  "R"         'reftex-toc-Rescan)
  5853.   (define-key map  "g"         'revert-buffer)
  5854.   (define-key map  "q"         'reftex-toc-quit)
  5855.   (define-key map  "Q"         'reftex-toc-quit-and-kill)
  5856.   (define-key map  "f"         'reftex-toc-toggle-follow)
  5857.   (define-key map  "x"         'reftex-toc-external)
  5858.   (loop for key across "0123456789" do
  5859.     (define-key map (vector (list key)) 'digit-argument))
  5860.   (define-key map "-" 'negative-argument))
  5861.  
  5862. ;;; Menus --------------------------------------------------------------------
  5863.  
  5864. ;; Define a menu for the menu bar if Emacs is running under X
  5865.  
  5866. (require 'easymenu)
  5867.  
  5868. (easy-menu-define
  5869.  reftex-mode-menu reftex-mode-map
  5870.  "Menu used in RefTeX mode"
  5871.  `("Ref"
  5872.    ["Table of Contents"       reftex-toc t]
  5873.    "----"
  5874.    ["\\label"                 reftex-label t]
  5875.    ["\\ref"                   reftex-reference t]
  5876.    ["\\cite"                  reftex-citation t]
  5877.    ["View Crossref"           reftex-view-crossref t]
  5878.    "----"
  5879.    ("Parse Document"
  5880.     ["Only this File"         reftex-parse-one t]
  5881.     ["Entire Document"        reftex-parse-all (reftex-is-multi)]
  5882.     ["Save to File"           (reftex-access-parse-file 'write)
  5883.      (> (length (symbol-value reftex-docstruct-symbol)) 0)]
  5884.     ["Restore from File"      (reftex-access-parse-file 'restore) t]
  5885.     "----"
  5886.     ["Enable Partial Scans" 
  5887.      (setq reftex-enable-partial-scans (not reftex-enable-partial-scans))
  5888.      :style toggle :selected reftex-enable-partial-scans]
  5889.     ["Auto-Save Parse Info"
  5890.      (setq reftex-save-parse-info (not reftex-save-parse-info))
  5891.      :style toggle :selected reftex-save-parse-info]
  5892.     "---"
  5893.     ["Reset RefTeX Mode"       reftex-reset-mode t])
  5894.    ("Global Actions"
  5895.     ["Search Whole Document"  reftex-search-document t]
  5896.     ["Replace in Document"    reftex-query-replace-document t]
  5897.     ["Grep on Document"       reftex-grep-document t]
  5898.     "----"
  5899.     ["Create TAGS File"       reftex-create-tags-file t]
  5900.     "----"
  5901.     ["Find Duplicate Labels"  reftex-find-duplicate-labels t]
  5902.     ["Change Label and Refs"  reftex-change-label t]
  5903.     ;;;["Renumber Simple Labels" reftex-renumber-simple-labels t]
  5904.     "---"
  5905.     ["Save document"          reftex-save-all-document-buffers t])
  5906.    "---"
  5907.    ("Reference Options"
  5908.     "Varioref Setting"
  5909.     ["Use `\\vref' by Default" 
  5910.      (setq reftex-vref-is-default (not reftex-vref-is-default))
  5911.      :style toggle :selected reftex-vref-is-default]
  5912.     "---"
  5913.     "Selection Buffers"
  5914.     ["Use Multiple Buffers"
  5915.      (setq reftex-use-multiple-selection-buffers
  5916.        (not reftex-use-multiple-selection-buffers))
  5917.      :style toggle :selected reftex-use-multiple-selection-buffers]
  5918.     ["Auto Update Buffers"
  5919.      (setq reftex-auto-update-selection-buffers
  5920.        (not reftex-auto-update-selection-buffers))
  5921.      :style toggle :selected reftex-auto-update-selection-buffers])
  5922.    ("Citation Options"
  5923.     "Citation Style"
  5924.     ,@(mapcar
  5925.        (function
  5926.     (lambda (x)
  5927.       (vector
  5928.        (capitalize (symbol-name (car x)))
  5929.        (list 'setq 'reftex-cite-format (list 'quote (car x)))
  5930.        ':style 'radio ':selected
  5931.        (list 'eq 'reftex-cite-format (list 'quote (car x))))))
  5932.     reftex-cite-format-builtin)
  5933.     "----"
  5934.     "Bibinfo in Comments"
  5935.     ["Attach Comments"
  5936.      (setq reftex-comment-citations (not reftex-comment-citations))
  5937.      :style toggle :selected reftex-comment-citations]
  5938.     "---"
  5939.     "Sort Database Matches"
  5940.     ["by Author" (setq reftex-sort-bibtex-matches 'author)
  5941.      :style radio :selected (eq reftex-sort-bibtex-matches 'author)]
  5942.     ["by Year" (setq reftex-sort-bibtex-matches 'year)
  5943.      :style radio :selected (eq reftex-sort-bibtex-matches 'year)]
  5944.     ["by Year, reversed" (setq reftex-sort-bibtex-matches 'reverse-year)
  5945.      :style radio :selected (eq reftex-sort-bibtex-matches 'reverse-year)]
  5946.     ["Not" (setq reftex-sort-bibtex-matches nil)
  5947.      :style radio :selected (eq reftex-sort-bibtex-matches nil)])
  5948.    ("Customize"
  5949.     ["Browse RefTeX group" reftex-customize t]
  5950.     "---"
  5951.     ["Build Full Customize Menu" reftex-create-customize-menu 
  5952.      (fboundp 'customize-menu-create)])
  5953.    "----"
  5954.    ("Documentation"
  5955.     ["Info" reftex-info t]
  5956.     ["Commentary" reftex-show-commentary t])))
  5957.  
  5958. ;;; Run Hook ------------------------------------------------------------------
  5959.  
  5960. (run-hooks 'reftex-load-hook)
  5961.  
  5962. ;;; That's it! ----------------------------------------------------------------
  5963.  
  5964. (provide 'reftex) 
  5965.  
  5966. ; Make sure tables are compiled
  5967. (message "updating internal tables...")
  5968. (reftex-compute-ref-cite-tables)
  5969. (message "updating internal tables...done")
  5970. (setq reftex-tables-dirty nil)
  5971.  
  5972. ;;;============================================================================
  5973.  
  5974. ;;; reftex.el ends here
  5975.  
  5976.